我有以下代码:
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];
}
}
为什么我不能为我的泛型方法创建委托(delegate)?我知道我可以只使用 mi.Invoke(this, null)
,但由于我可能要执行 SomeMethod
几百万次,所以我想能够创建一个委托(delegate)并将其缓存为一个小的优化。
最佳答案
你的方法不是静态方法,所以你需要使用:
Func<IEnumerable<int>> reflection_delgate = (Func<IEnumerable<int>>)Delegate.CreateDelegate(typeof(Func<IEnumerable<int>>), this, mi);
将“this”传递给第二个参数将允许该方法绑定(bind)到当前对象上的实例方法...
关于c# - 使用反射创建通用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2419705/