要从方法创建委托,您可以使用编译类型安全语法:
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 方法创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!