je le code suivant:délégué générique utilisant la réflexion
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];
}
}
Pourquoi ne puis-je créer un délégué à ma méthode générique? Je sais que je pourrais juste utiliser mi.Invoke(this, null)
, mais puisque je vais vouloir exécuter SomeMethod
potentiellement plusieurs millions de fois, j'aimerais pouvoir créer un délégué et le mettre en cache comme une petite optimisation.
Doh! Merci beaucoup - je ne sais pas comment j'ai raté ça. – Dathan