简体   繁体   中英

How to get a getter of a property?

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.

var getter = typeof(DateTime).GetProperty("Now").GetGetMethod();
var func = Delegate.CreateDelegate(getter, typeof(Func<DateTime>)) 
               as Func<DateTime>;

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()

只是另一种变体:

Func<int> getCurrentValue = delegate { return IntValue; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM