Retrieving the MethodInfo of of the correct overload of a generic method

前端 未结 5 873
误落风尘
误落风尘 2021-01-02 09:25

I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func parameter) using reflection. T

5条回答
  •  没有蜡笔的小新
    2021-01-02 09:49

    You need to specify a concrete type using MethodInfo.MakeGenericMethod.

    However, I should point out, that getting the right type to invoke MakeGenericMethod on is not easy when you have an overloaded generic method.

    Here is an example:

    var method = typeof(Foo)
                     .GetMethods()
                     .Where(x => x.Name == "Bar")
                     .Where(x => x.IsGenericMethod)
                     .Where(x => x.GetGenericArguments().Length == 1)
                     .Where(x => x.GetParameters().Length == 1)
                     .Where(x => 
                         x.GetParameters()[0].ParameterType == 
                         typeof(Action<>).MakeGenericType(x.GetGenericArguments()[0])
                     )
                     .Single();
    
     method = method.MakeGenericMethod(new Type[] { typeof(int) });
    
     Foo foo = new Foo();
     method.Invoke(foo, new Func[] { () => return 42; });
    

提交回复
热议问题