问题
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;
}
}
What I would like to do is add an Attribute to the HelloPhrase property, like this
[MyCustomAttribute("Hello_Phrase")]
public string SayHello { 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();
}
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.
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];
回答1:
You can't do this. You cannot dynamically swap out the implementation of property getters and setters. The closest you can get are either:
- Dynamic proxies
- AOP libraries
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.)
But under no circumstance is there anything like SetGetMethod
or SetSetMethod
.
来源:https://stackoverflow.com/questions/6835726/replace-property-getter-setter-with-reflection-or-similar-no-3rd-party-librarie