I have the following code:
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];
}
}
Why can't I create a delegate to my generic method? I know I could just use mi.Invoke(this, null)
, but since I'm going to want to execute SomeMethod
potentially several million times, I'd like to be able to create a delegate and cache it as a small optimization.