12
创建泛型委托我有以下代码:使用反射
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
public void Run()
{
// works
Func<IEnumerable<int>> static_delegate = new Func<IEnumerable<int>>(SomeMethod<String>);
MethodInfo mi = this.GetType().GetMethod("SomeMethod").MakeGenericMethod(new Type[] { typeof(String) });
// throws ArgumentException: Error binding to target method
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), mi);
}
public IEnumerable<int> SomeMethod<T>()
{
return new int[0];
}
}
为什么我不能创建委托给我的泛型方法?我知道我可以使用mi.Invoke(this, null)
,但由于我想要执行SomeMethod
可能数百万次,我希望能够创建委托并将其缓存为小型优化。
Doh!非常感谢 - 不知道我是如何错过的。 – Dathan 2010-03-10 19:28:03