Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]; 
like image 404
Mike Miller Avatar asked Jul 26 '11 19:07

Mike Miller


1 Answers

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.

like image 178
Kirk Woll Avatar answered Sep 22 '22 06:09

Kirk Woll