[英]Pass in Generic Type to a method
Is this possible? 这可能吗?
When a type gets passed in to a method, I want to instantiate the generic class myClass 当类型传入方法时,我想实例化泛型类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)
) (
typeof(MyClass<>).MakeGenericType(myType)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.