Csharp/C#教程:Delegate.CreateDelegate()和generics:绑定到目标方法的错误分享


Delegate.CreateDelegate()和generics:绑定到目标方法的错误

我在使用reflection和generics创建委托集合时遇到问题。

我正在尝试从Ally方法创建一个委托集合,它们共享一个常用的方法签名。

public class Classy { public string FirstMethod( string id, Func<T1, int, IEnumerable> del ); public string SecondMethod( string id, Func<T1, int, IEnumerable> del ); public string ThirdMethod( string id, Func<T1, int, IEnumerable> del ); // And so on... } 

和仿制药烹饪:

 // This is the Classy's shared method signature public delegate string classyDelegate( string id, Func<T1, int, IEnumerable> filter ); // And the linq-way to get the collection of delegates from Classy ( from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof( classyDelegate ) select Delegate.CreateDelegate( delegateType, method ) ).ToList( ); 

但是Delegate.CreateDelegate( delegateType, method )抛出一个ArgumentException,表示Error绑定到target方法。 :/

我究竟做错了什么?

这是因为Delegate.CreateDelegate的重载仅支持创建指向静态方法的委托。 如果要绑定到实例方法,还需要传入创建的委托应该调用该方法的实例。

你可能想要:

 from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof( classyDelegate<,> ) select Delegate.CreateDelegate( delegateType, yourInstance, method ) 

此外,您的代码示例将无法编译。 您不能在方法签名上声明差异; 并且你不能在非抽象类中省略实现。

最后,Delegate.CreateDelegate创建一个Delegate 实例 ,如果不知道它的类型参数,它就不能存在。 因此,您无法绑定到classyDelegate <,>,您需要知道所涉及的实际类型。

上述就是C#学习教程:Delegate.CreateDelegate()和generics:绑定到目标方法的错误分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1013870.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐