小编典典

如何使用给定的Type对象调用泛型方法?[重复]

c#

这个问题已经在这里有了答案

如何使用反射调用泛型方法? (8个答案)

6年前关闭。

我想用给定的类型对象调用我的通用方法。

void Foo(Type t)
{
     MyGenericMethod<t>();
}

显然是行不通的。

我该如何运作?


阅读 404

收藏
2020-05-19

共1个答案

小编典典

您的代码示例将不起作用,因为通用方法需要类型标识符,而不是Type类的实例。您必须使用反射来做到这一点:

public class Example {

    public void CallingTest()
    {
        MethodInfo method = typeof (Example).GetMethod("Test");
        MethodInfo genericMethod = method.MakeGenericMethod(typeof (string));
        genericMethod.Invoke(this, null);

    }

    public void Test<T>()
    {
        Console.WriteLine(typeof (T).Name);
    }
}

请记住,这非常脆弱,我宁愿建议您找到另一种模式来调用您的方法。

另一个骇人听闻的解决方案(也许有人可以使其变得更干净)将使用一些表达魔术:

public class Example {

    public void CallingTest()
    {
        MethodInfo method = GetMethod<Example>(x => x.Test<object>());
        MethodInfo genericMethod = method.MakeGenericMethod(typeof (string));
        genericMethod.Invoke(this, null);

    }

    public static MethodInfo GetMethod<T>(Expression<Action<T>> expr)
    {
        return ((MethodCallExpression) expr.Body)
            .Method
            .GetGenericMethodDefinition();
    }

    public void Test<T>()
    {
        Console.WriteLine(typeof (T).Name);
    }
}

请注意在lambda中将“对象”类型标识符作为通用类型参数传递。无法如此迅速地找到解决方法。无论哪种方式,我认为这都是编译时安全的。只是感觉不对:/

2020-05-19