检索泛型方法的正确超负荷的MethodInfo的 [英] Retrieving the MethodInfo of of the correct overload of a generic method

查看:122
本文介绍了检索泛型方法的正确超负荷的MethodInfo的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类型包含一个通用方法的两个重载。我想找回重载之一(与 Func键< 参数; T&GT)使用反射。但问题是,我无法找到正确的参数类型与供给 Type.GetMethod(字符串类型[])方法。

I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func<T> parameter) using reflection. The problem however is that I can't find the correct parameter type to supply the Type.GetMethod(string, Type[]) method with.

下面是我的类定义:

public class Foo
{
    public void Bar<T>(Func<T> f) { }
    public void Bar<T>(Action<T> a) { }
}

这是我想出来的,可惜没有更迭:

And this is what I've come up with, unfortunately without succes:

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

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

    Assert.IsNotNull(method); // Fails
}

我怎样才能获得的MethodInfo 的通用方法,我知道的参数?

How can I get the MethodInfo of a generic method of which I know the parameters?

推荐答案

你为什么不使用EX pression树?这使得它更容易:

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

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);
}

这篇关于检索泛型方法的正确超负荷的MethodInfo的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆