Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a getter of a property?

Tags:

c#

properties

I would like to get a getter of a property so I could pass to a method that requires Func. For now I extracted getter to a Get method and I use this method when I need the getter function.

Few words about background: I have class A with properties and I have another class T which keeps track of some properties from A (and from class B, C, etc.). Keeping track means here that when object of T is asked about current values of tracked properties it should give such.

One approach could be change notification mechanism, but class A does not know what is tracked or not -- so it is quite wrong approach. You have to rewrite all classes that might be tracked. Moreover notifications have to be send all the time, even if tracker won't be asked about values at all.

It seems more handy to simply pass a method how to read the value (getter of property) and tracker will use it when required. No overhead, pretty straightforward.

like image 264
greenoldman Avatar asked Dec 16 '22 23:12

greenoldman


2 Answers

Compiled code, or reflection? As a delegate, you can just use:

Func<Foo, int> func = x => x.SomeValue;

or to track the specific object:

Func<int> funct = () => someObj.SomeValue;

With reflection you would need GetGetMethod() and Delegate.CreateDelegate()

like image 60
Marc Gravell Avatar answered Jan 03 '23 07:01

Marc Gravell


var getter = typeof(DateTime).GetProperty("Now").GetGetMethod();
var func = Delegate.CreateDelegate(getter, typeof(Func<DateTime>)) 
               as Func<DateTime>;
like image 38
leppie Avatar answered Jan 03 '23 06:01

leppie