Replace Property Getter/Setter with Reflection or similar (no 3rd party libraries) in c#

此生再无相见时 提交于 2019-12-08 21:02:01

问题


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:

  1. Dynamic proxies
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!