问题描述
例如,我有一个包含在类中的属性
I've got a property contained in a class for example
public class Greeter {
private Hashtable _data;
public string HelloPhrase { get; set; }
public Greeter(data) {
_data = data;
}
}
我想做的是将一个属性添加到HelloPhrase属性,例如
What I would like to do is add an Attribute to the HelloPhrase property, like this
[MyCustomAttribute("Hello_Phrase")]
public string SayHello { get; set; }
这样,在构造函数期间,我可以对MyCustomAttribute具有的Class(Greeter)中的属性进行反思被定义并将属性的Get / Set方法设置为匿名方法/委托。
Such that during the constructor I can reflect over the Properties in the Class(Greeter) where MyCustomAttribute has been defined and set the Get/Set methods of the property to an anonymous method / delegate.
public Greeter(data) {
_data = data;
ConfigureProperties();
}
我设法从类中获取了PropertyInfo,但这仅公开了GetSetMethod (http://msdn.microsoft.com/zh-cn/library/system.reflection.propertyinfo.getsetmethod.aspx)和相应的GetGetMethod。
I've managed to get the PropertyInfo's from the class but this only exposes GetSetMethod (http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx) and the corresponding GetGetMethod.
在这里和在线阅读一些问题,但找不到不使用某种Aspects库的答案。
I've read through some of the questions here and online but can't find an answer that doesn't use an Aspects library of some sort.
任何人都可以通过提供程序来设置在运行时获取/设置方法?理想情况下,对于
Could anyone provider pointers to setting the Get/Set methods at runtime? Ideally to a delegate like
x =>_data[keyDefinedByAttribute];
推荐答案
您不能执行此操作。您不能动态地换出属性getter和setter的实现。您可以获得的最接近的值是:
You can't do this. You cannot dynamically swap out the implementation of property getters and setters. The closest you can get are either:
- AOP库
动态代理可能适合您,也可能不适合您,但是IMO我更喜欢使用解决方案而不是方面的解决方案。但是,动态行为将在代理类中出现(通过接口或通过动态子类化并覆盖您的虚拟属性)。
Dynamic proxies may or may not suit you, but IMO I'd much prefer a solution that uses that over aspects. However, the dynamic behavior will be surfaced in a proxy class (either of an interface or by dynamically subclassing and overriding your virtual properties.)
但是在任何情况下都没有任何东西例如 SetGetMethod
或 SetSetMethod
。
But under no circumstance is there anything like SetGetMethod
or SetSetMethod
.
这篇关于用C#中的Reflection或类似代码(没有第三方库)替换Property Getter / Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!