将通用类型传递给方法 [英] Pass in Generic Type to a method
本文介绍了将通用类型传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是可能的吗?
当一个类型被传入一个方法时,我想实例化泛型类myClass
public class myClass< T>
{
}
公共无效PassInType(类型的myType)
{
myClass的<的myType> c = new myClass< myType>();
}
更新:
因为这就是好不可能的,我怎么做此
公共myMethod的(字符串的myType)
{
myClass< myType> c = new myClass< myType>();
$ div $解析方案
不;这是根本不可能的。
泛型的要点是它们会创建编译时间类型。试图创建一个在编译时未知的类型。
尽管如此,您可以使用反射来完成。 ( typeof(MyClass<>)MakeGenericType(myType)
)
Is this possible?
When a type gets passed in to a method, I want to instantiate the generic class myClass
public class myClass<T>
{
}
public void PassInType(Type myType)
{
myClass<myType> c=new myClass<myType>();
}
Update:
Okay since thats not possible, how do I do this
public myMethod(string myType)
{
myClass<myType> c=new myClass<myType>();
}
解决方案
No; that's fundamentally impossible.
The whole point of generics is that they create compile-time types.
You're trying to create a type which is unknown at compile time.
You can do it using reflection, though. (typeof(MyClass<>).MakeGenericType(myType)
)
这篇关于将通用类型传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文