C#:在运行时获取类型参数传递到一个泛型方法 [英] C# : Get type parameter at runtime to pass into a Generic method

查看:1412
本文介绍了C#:在运行时获取类型参数传递到一个泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

泛型方法是...

    public void PrintGeneric2<T>(T test) where T : ITest
    {
        Console.WriteLine("Generic : " + test.myvar);
    }



我打电话这主要来自()...

I'm calling this from Main()...

    Type t = test2.GetType();       
    PrintGeneric2<t>(test2);



我得到错误CS0246:类型或命名空间名称'T'找不到和 CS1502:最好的重载的方法匹配DoSomethingClass.PrintGeneric2< T>(T)的参数无效

I get error "CS0246: the type or namespace name 't' could not be found" and "CS1502: best overloaded method match DoSomethingClass.PrintGeneric2< t >(T) has invalid arguments"

这是关系到我以前在这里的问题:的C#:传递一个通用对象

this is related to my previous question here: C# : Passing a Generic Object

我读过了泛型类型不能在运行时确定,而无需使用反射或MethodInfo的,但我不是如何在这种情况下做到这一点非常明确。

I've read that the generic type can't be determined at runtime, without the use of reflection or methodinfo, but I'm not very clear on how to do so in this instance.

感谢,如果你能赐教=)

Thanks if you can enlighten me =)

推荐答案

如果你真的想用一个类型参数不是调用一个泛型方法在编译时已经知道,你可以写这样的:

If you really want to invoke a generic method using a type parameter not known at compile-time, you can write something like:

typeof(YourType).GetMethod("PrintGeneric2").MakeGenericMethod(t).Invoke(instance, new object[] { test2 } );



然而,正如其他答复指出,仿制药可能不是你的情况最好的解决方案。

However, as stated by other responses, Generics might not be the best solution in your case.

这篇关于C#:在运行时获取类型参数传递到一个泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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