【发布时间】:2012-12-11 16:39:08
【问题描述】:
我正在尝试使用Delegate.CreateDelegate [MSDN link] 绑定到静态泛型方法,但绑定失败。
这是PoC代码:
public static class CreateDelegateTest {
public static void Main() {
Action actionMethod = CreateDelegateTest.GetActionDelegate();
Action<int> intActionMethod = CreateDelegateTest.GetActionDelegate<int>();
Func<int> intFunctionMethod = CreateDelegateTest.GetFunctionDelegate<int>();
}
public static Action GetActionDelegate() {
return (Action)Delegate.CreateDelegate(typeof(Action), typeof(CreateDelegateTest), "ActionMethod");
}
public static Action<T> GetActionDelegate<T>() {
return (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), typeof(CreateDelegateTest), "GenericActionMethod");
}
public static Func<TResult> GetFunctionDelegate<TResult>() {
return (Func<TResult>)Delegate.CreateDelegate(typeof(Func<TResult>), typeof(CreateDelegateTest), "GenericFunctionMethod");
}
public static void ActionMethod() { }
public static void GenericActionMethod<T>(T arg) { }
public static TResult GenericFunctionMethod<TResult>() {
return default(TResult);
}
}
actionMethod 已正确创建,但 intActionMethod 和 intFunctionMethod 创建抛出。
为什么CreateDelegate 无法绑定到泛型方法?如何绑定它们?
我已在 Microsoft Connect [link] 上提交了错误。如果您认为这是一个错误,请投票给它。
更新 2: 我错误地认为绑定到非函数泛型方法会成功。原来任何泛型方法都绑定失败。
【问题讨论】:
-
这不是错误。您通常会依赖编译器的类型推断来创建您要调用的特定方法的实例,即处理特定类型的方法。 CreateDelegate() 不会为您执行此操作,您必须帮助并显式创建该方法。 MethodInfo.MakeGenericMethod() 是必需的。
-
@HansPassant 原来我错误地认为绑定适用于非函数泛型方法。这实际上发生在所有泛型方法中。
标签: c# generics reflection static delegates