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

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

    Why don't you use expression trees? This makes it much easier:

    public static MethodInfo GetMethod(
        Expression> methodSelector)
    {
        var body = (MethodCallExpression)methodSelector.Body;
        return body.Method;      
    }
    
    [TestMethod]
    public void Test1()
    {
        var expectedMethod = typeof(Foo)
            .GetMethod("Bar", new Type[] { typeof(Func<>) });
    
        var actualMethod = 
            GetMethod(foo => foo.Bar((Func)null)
            .GetGenericMethodDefinition();
    
        Assert.AreEqual(expectedMethod, actualMethod);
    }
    
        

    提交回复
    热议问题