【问题标题】:Pass in Generic Type to a method将通用类型传递给方法
【发布时间】:2012-12-05 22:28:59
【问题描述】:

这可能吗?

当一个类型被传入一个方法时,我想实例化泛型类 myClass

public class myClass<T>
{

}

public void PassInType(Type myType)
{

myClass<myType> c=new myClass<myType>();
}

更新:

好的,既然这不可能,我该怎么做

public myMethod(string myType)
{

myClass<myType> c=new myClass<myType>();

}

【问题讨论】:

  • 请添加语言标签。

标签: c# generics


【解决方案1】:

没有;这是根本不可能的。

泛型的全部意义在于它们创建编译时类型。
您正在尝试创建一个在编译时未知的类型。

不过,您可以使用反射来实现。 (typeof(MyClass&lt;&gt;).MakeGenericType(myType))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多