如何调用泛型方法与给定类型的对象? [英] How to call generic method with a given Type object?

查看:219
本文介绍了如何调用泛型方法与给定类型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要与给定类型的对象叫我的一般方法。

I want to call my generic method with a given type object.

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

显然是行不通的。

obviously doesn't work.

我怎样才能使它工作?

推荐答案

您code样品将无法正常工作,因为通用的方法需要一个类型标识符,Type类不是一个实例。你将不得不使用反射来做到这一点:

Your code sample won't work, because the generic method expects a type identifier, not a an instance of the Type class. You'll have to use reflection to do it:

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

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

Do keep in mind that this is very brittle, I'd rather suggest finding another pattern to call your method.

另外一个哈克解决方案(也许有人可以把它有点清洁剂)会使用一些EX pression魔法:

Another hacky solution (maybe someone can make it a bit cleaner) would be to use some expression magic:

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

请注意传递的对象类型标识符作为拉姆达一个泛型类型参数。无法弄清楚这么快怎么去解决这一问题。无论哪种方式,这是编译时的安全,我认为。它只是感觉错了不知何故:/

Note passing the 'object' type identifier as a generic type argument in the lambda. Couldn't figure out so quickly how to get around that. Either way, this is compile-time safe I think. It just feels wrong somehow :/

这篇关于如何调用泛型方法与给定类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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