检索泛型方法的正确重载的MethodInfo

Ann*_*nne 9 .net c# generics reflection

我有这种类型,包含泛型方法的两个重载.我喜欢Func<T>使用反射检索其中一个重载(使用参数).但问题是我找不到正确的参数类型来提供Type.GetMethod(string, Type[])方法.

这是我的班级定义:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}
Run Code Online (Sandbox Code Playgroud)

这是我想出来的,不幸的是没有成功:

[TestMethod]
public void Test1()
{
    Type parameterType = typeof(Func<>);

    var method = typeof(Foo).GetMethod("Bar", new Type[] { parameterType });

    Assert.IsNotNull(method); // Fails
}
Run Code Online (Sandbox Code Playgroud)

如何获得MethodInfo我知道参数的通用方法?

Ste*_*ven 10

你为什么不使用表达式树?这使它更容易:

public static MethodInfo GetMethod<T>(
    Expression<Action<T>> 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 => foo.Bar<object>((Func<object>)null)
        .GetGenericMethodDefinition();

    Assert.AreEqual(expectedMethod, actualMethod);
}
Run Code Online (Sandbox Code Playgroud)