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

前端 未结 5 857
误落风尘
误落风尘 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:38

    Surprisingly, it looks like you'll need to call GetMethods() and loop over the methods until you find the one you want.

    For example:

    var yourMethod = typeof(Foo).GetMethods()
        .First(m => m.Name == "Bar" 
                 && m.GetParameters().Length == 1
                 && m.GetParameters()[0].ParameterType.ContainsGenericParameters
                 && m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Func<>));
    

提交回复
热议问题