从属性getter或setter方法创建一个委托 [英] Create a delegate from a property getter or setter method
问题描述
要创建一个方法的委托可以使用编译类型安全的语法:
To create a delegate from a method you can use the compile type-safe syntax:
private int Method() { ... }
// and create the delegate to Method...
Func<int> d = Method;
一个属性是围绕一个getter和setter方法的包装,我想创建一个委托到物业getter方法。类似
A property is a wrapper around a getter and setter method, and I want to create a delegate to a property getter method. Something like
public int Prop { get; set; }
Func<int> d = Prop;
// or...
Func<int> d = Prop_get;
不工作,很遗憾。我要创建一个单独的lambda方法,似乎没有必要当getter方法的委托签名反正匹配:
Which doesn't work, unfortunately. I have to create a separate lambda method, which seems unnecessary when the getter method matches the delegate signature anyway:
Func<int> d = () => Prop;
为了直接使用委托方法,我都用讨厌的反射,这是不编译类型安全的:
In order to use the delegate method directly, I have to use nasty reflection, which isn't compile type-safe:
// something like this, not tested...
MethodInfo m = GetType().GetProperty("Prop").GetGetMethod();
Func<int> d = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), m);
有没有直接在编译安全的方式创建一个属性获取方法的委托的任何方式,类似于创建在顶部有一个正常的方法的委托,而无需使用中间的lambda方法?
Is there any way of creating a delegate on a property getting method directly in a compile-safe way, similar to creating a delegate on a normal method at the top, without needing to use an intermediate lambda method?
推荐答案
至于我可以告诉大家,你已经写下来所有的有效的变种。因为它是不可能明确解决普通代码getter或setter(无反射,这是),我不认为有一种方法可以做你想做的。
As far as I can tell, you have already written down all "valid" variants. Since it isn't possible to explicitly address a getter or setter in normal code (without reflection, that is), I don't think that there is a way to do what you want.
这篇关于从属性getter或setter方法创建一个委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!