【发布时间】:2010-03-10 19:01:41
【问题描述】:
我有以下代码:
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 数百万次,我希望能够创建一个委托并将其缓存为一个小的优化。
【问题讨论】:
标签: c# .net generics reflection delegates