In C#, there is not built-in operator or method to retrieve a MethodInfo instance from a generic method (AFAIK).
One way way to achieve this, is to use expression trees (this is quite popular see here, here or here) :
public static MethodInfo GetMethodInfoA<T>(Expression<T> methodSelector)
{
var body = (MethodCallExpression)methodSelector.Body;
return body.Method;
}
public static bool Foo<T>(T a, T b)
{
return a.Equals(b);
}
//How to use it :
GetMethodInfoA<Func<int, int, bool>>((x, y) => Foo(x, y));
Here is the code I used so far (before discovering the expression tree solution) :
public static MethodInfo GetMethodInfoB<T>(T func)
{
Delegate del = (Delegate)(object)func;
MethodInfo method = del.Method;
return method;
}
//usage is similar (but shorter):
GetMethodInfoB<Func<int, int, bool>>(Foo);
From what i tested so far, both works and produce similar results. My question is : is there any difference between these two methods ? (except one take an expression the other an object) I am thinking of a special case where one would work and not the other, or performance issues.
Note : both can fail at runtime, if wrong arguments are passed :
GetMethodInfoA<Func<int>>(() => 0); //bang
GetMethodInfoB<int>(0); //here as well
Aucun commentaire:
Enregistrer un commentaire