问题描述
我在使用反射和泛型创建委托集合时遇到问题.
I'm having problems creating a collection of delegate using reflection and generics.
我正在尝试从 Ally 方法创建一个委托集合,这些方法共享一个公共方法签名.
I'm 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 );
public string ThirdMethod<T1, T2>( string id, Func<T1, int, IEnumerable<T2>> del );
// And so on...
}
还有泛型烹饪:
// This is the Classy's shared method signature
public delegate string classyDelegate<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> 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 binding to target method.:/
But the Delegate.CreateDelegate( delegateType, method )
throws an ArgumentException saying Error binding to target method. : /
我做错了什么?
推荐答案
那是因为Delegate.CreateDelegate的重载只支持创建指向静态方法的委托.如果要绑定到实例方法,还需要传入您创建的委托应该调用该方法的实例.
That is because the overload of 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 | BindingFlags.NonPublic )
let delegateType = typeof( classyDelegate<,> )
select Delegate.CreateDelegate( delegateType, yourInstance, method )
另外,您的代码示例无法编译.您不能在方法签名上声明方差;并且不能省略非抽象类中的实现.
Also, your code example won't compile. You 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 a Delegate instance, which cannot exist without knowing it's type parameters. Therefore, you cannot bind to classyDelegate<,>, you need to know the actual types involved.
这篇关于Delegate.CreateDelegate() 和泛型:错误绑定到目标方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!