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

1

7

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]; 
Cepeda answered 26/7, 2011 at 19:52 Comment(0)
T
4

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.

Testis answered 26/7, 2011 at 19:58 Comment(3)
Thanks I was beginning to think that was the case which isn't a big issue for me. I'll probably try it with unity interception as I know that and then look around at lighter weight libraries.Cepeda
Can you express why you think proxies are superior to AOP?Lyndialyndon
I guess the way I'd look at it, @crush, is that dynamic proxies is a tiny subset of what AOP provides, and therefore its potential impact is constrained. YMMV.Testis

© 2022 - 2024 — McMap. All rights reserved.