Is there a good way to get MethodInfo an open public method?

Consider a type like this

public interface IHaveGenericMethod
{
   T1 Method<T1>(T1 parm);
   T2 Method<T1,T2>(T1 parm);
   int Method2(int parm);
}

How do I get methodInfo for its methods? for a regular non-generic method like method2, I can go with

typeof(IHaveGenericMethod).GetMethod("methodName",new Type[]{typeof(itsParameters)});

for the general method, however, I cannot, since parameters are not types per se. So how do I do this? I know I can call

typeof(IHaveGenericMethod).GetMethods()

to get all the methods of this type and then iterate over this collection and perform some match, but it's ugly. Is there a better way?

+3
source share
3 answers

Well, these are types - like:

    foreach (var method in typeof(IHaveGenericMethod).GetMethods())
    {
        Console.WriteLine(method.Name);
        if (method.IsGenericMethodDefinition)
        {
            foreach (Type type in method.GetGenericArguments())
            {
                Console.WriteLine("> " + type.Name);
            }
        }
    }

This way you can check the number of arguments and verify the signature. But nothing is cleaner.

+1

MSDN "" ".

per-se

, , , , , GetMethod(), .

, , , " " , - . .

, :

       var mi = from mi in typeof(IHaveGenericMethod).GetMethods()
                where mi.Name == "Method"
                where mi.IsGenericMethodDefinition
                where mi.GetGenericArguments().Length == 2
                select mi;
+2

:

public static MethodInfo ExtractMethodInfo<TDeclaringType, TMethod>(Expression<Func<TDeclaringType, TMethod>> methodAccessExpression) {
    return (MethodInfo)((ConstantExpression)((MethodCallExpression)((UnaryExpression)methodAccessExpression.Body).Operand).Object).Value;
}

var genericQueryMethodInfo = ExpressionHelper.ExtractMethodInfo<DbContext, Func<IQueryable<object>>>(context => context.Query<object>).GetGenericMethodDefinition();
0

All Articles