问题描述
我在使用反射和泛型创建委托集合时遇到问题.
I'm having problems creating a collection of delegate using vpn下载 reflection vpn下载 and generics.
我正在尝试从 Ally 方法创建一个委托集合,这些方法共享一个公共方法签名.
I'm 免费vpn下载 trying to create a delegate collection from Ally methods, whose share a common method signature.
public class Classy
{
public string FirstMethod<T1, T2>( string id, Func<T1, int, IEnumerable<T2>> del );
public string SecondMethod<T1, T2>( string id, Func<T1, int, IEnumerable<T2>> del vpn下载 );
vpn下载 public vpn free string ThirdMethod<T1, T2>( string id, Func<T1, int, 免费vpn IEnumerable<T2>> del 免费vpn );
// And so on...
}
还有泛型烹饪:
// This is the Classy's shared 免费vpn method vpn下载 signature
public delegate string classyDelegate<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> filter vpn free );
// And the linq-way to get the collection free vpn of delegates from Classy
(
free vpn from method in typeof( 免费vpn Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly free vpn | BindingFlags.NonPublic )
let delegateType = typeof( classyDelegate<,> )
select Delegate.CreateDelegate( delegateType, method )
).ToList( );
但是 Delegate.CreateDelegate(delegateType, method) 抛出一个 ArgumentException 说 Error binding to target method.:/
But the Delegate.CreateDelegate( delegateType, method 免费vpn ) throws an ArgumentException saying Error binding to target method. : /
我做错了什么?
推荐答案
那是因为Delegate.CreateDelegate的重载只支持创建指向静态方法的委托.如果要绑定到实例方法,还需要传入您创建的委托应该调用该方法的实例.
That is because the overload of vpn下载 Delegate.CreateDelegate only supports creating delegates pointing to static methods. If you want to bind to instance methods, you also need to pass in the instance on which your created delegate is supposed to call the method.
你可能想要:
from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly vpn下载 | BindingFlags.NonPublic )
let delegateType 免费vpn = typeof( classyDelegate<,> )
select Delegate.CreateDelegate( delegateType, vpn下载 yourInstance, method )
另外,您的代码示例无法编译.您不能在方法签名上声明方差;并且不能省略非抽象类中的实现.
Also, 免费vpn your 免费vpn code example won't compile. You 免费vpn下载 can't declare variance on method signatures; and you can't omit the implementation in a non-abstract class.
最后,Delegate.CreateDelegate 创建了一个Delegateinstance,如果不知道它的类型参数就无法存在.因此,您不能绑定到 classyDelegate<,>,您需要知道所涉及的实际类型.
Finally, Delegate.CreateDelegate creates 免费vpn a Delegate instance, which cannot exist without knowing it's type parameters. Therefore, 免费vpn下载 you cannot bind to classyDelegate<,>, you need 免费vpn下载 to know the actual types involved.
这篇关于Delegate.CreateDelegate() 和泛型:错误绑定到目标方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构免费vpn源码(带手机端)
高端HTML5响应式企业集团通用类免费vpn织梦模板(自适应手机端)