C#:在运行时获取类型参数以传递给泛型方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9666064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# : Get type parameter at runtime to pass into a Generic method
提问by user1229895
The generic Method is...
泛型方法是...
public void PrintGeneric2<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
I'm calling this from Main()...
我从 Main() 调用它...
Type t = test2.GetType();
PrintGeneric2<t>(test2);
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"
我收到错误“CS0246:找不到类型或命名空间名称‘t’”和“CS1502:最佳重载方法匹配 DoSomethingClass.PrintGeneric2<t>(T) 的参数无效”
this is related to my previous question here: C# : Passing a Generic Object
这与我之前的问题有关:C# : Passing a Generic Object
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 =)
谢谢你,如果你能启发我=)
回答by Moo-Juice
Just call:
只需致电:
PrintGeneric2(test2);
The compiler will infer <t>from what you pass.
编译器将<t>根据您传递的内容进行推断。
回答by Adrian Zanescu
Generics offer Compile Timeparametric polymorphism. You are trying to use them with a type specified only at Runtime. Short answer : it won't work and it has no reason to (except with reflection but that is a different beast altogether).
泛型提供编译时参数多态性。您正在尝试将它们与仅在Runtime指定的类型一起使用。简短的回答:它不会起作用,也没有理由(除了反射,但那是完全不同的野兽)。
回答by Matthias
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.
但是,正如其他回复所述,在您的情况下,泛型可能不是最佳解决方案。

