注入/处理属性获取器/设置器?
我编写了一个抽象类,用于自动执行许多 INotifyPropertyChanged 和 IDataErrorInfo 内容。然而,这要求我指定一个自定义 getter/setter,它为每个属性调用自定义方法。
为了避免额外的输入,我一直在尝试找到一种方法来覆盖/处理对象中的属性 getter/setter 并调用自定义方法而不是生成的 getter/setter。
我尝试从 DynamicObject 继承并重写 TryGetMember 和 TrySetMember,但是这些方法似乎仅在对象声明为动态时才有效。
所以我想知道我想要实现的目标是否可以通过 .NET 反射或其他一些机制实现,还有是否可以检测属性 setter/getter 是否已在代码中定义?
谢谢, 亚历克斯.
I have written an abstract class that I am using to automate a lot of INotifyPropertyChanged and IDataErrorInfo stuff. However this requires that I specify a custom getter/setter which calls a custom method for every property.
To avoid the extra typing I have been trying to find a way to override/handle the property getters/setters in an object and call the custom method instead of the generated getter/setter.
I tried inheriting from DynamicObject and overriding TryGetMember and TrySetMember, however these methods only seem to work if the object is declared as dynamic.
So I want to know if what I am trying to achieve is possible at all through .NET reflection or some other mechanism, also is there anyway to detect if the property setter/getter has been defined in code?
Thanks,
Alex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Type.GetProperties 方法获取有关类型属性的信息。您将收到 PropertyInfo 对象的集合。这些对象具有
CanRead
和CanWrite
属性,表示属性是否可读/可写。要覆盖此行为,您必须:
对于免费解决方案,您最好使用 城堡动态代理。如果您准备花一些钱,请查看 PostSharp,它已经实现了许多类似性质的功能。像 INotifyProperty chage、撤消/重做等。您还可以查看任何支持方面编织的 AOP 框架,但对于您所描述的情况,我会选择 DynamicProxy。
You can get information about properties of a type using Type.GetProperties method. You will receive a collection of PropertyInfo object. Those object have
CanRead
andCanWrite
properties which say if properties are readable/writable.To override this behavior you would have to:
For free solutions you are best to use Castle DynamicProxy. If you are ready to spend some money, take a look at PostSharp which already implements many things of similar nature. Like INotifyProperty chage, undo/redo etc. You could also take a look at any AOP framework which supports aspect weaving, but DynamicProxy would be my pick for situation you described.