若要从方法创建委托,可以使用编译类型安全语法:
private int Method() { ... }
// and create the delegate to Method...
Func<int> d = Method;
属性是getter和setter方法的包装器,我想创建一个属性getter方法的委托。就像这样
public int Prop { get; set; }
Func<int> d = Prop;
// or...
Func<int> d = Prop_get;
不幸的是,这不起作用。我必须创建一个单独的lambda方法,当getter方法与委托签名匹配时,这似乎没有必要:
Func<int> d = () => Prop;
为了直接使用委托方法,我必须使用讨厌的反射,这不是编译类型安全的:
// something like this, not tested...
MethodInfo m = GetType().GetProperty("Prop").GetGetMethod();
Func<int> d = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), m);
有没有办法以编译安全的方式直接在属性获取方法上创建委托,类似于在顶部的普通方法上创建委托,而不需要使用中间的lambda方法?
https://stackoverflow.com/questions/2621488
复制相似问题