【问题标题】:Dynamic type instance creation [duplicate]动态类型实例创建[重复]
【发布时间】:2017-04-17 14:49:23
【问题描述】:

我在使用动态类型来实例化自定义类时遇到问题。 例如,我有以下课程:

public class myClass<T>
{
    public myClass(String header);
}

如果我使用以下代码,一切正常:

var myInstance = new myClass<int>("myHeader");

但是,我没有定义 int 类型,因此我需要从泛型类型参数动态转换它。到目前为止我尝试了什么:

1.

    Type myType = typeof(int);
    var myInstance = new myClass<myType>("myHeader");

2.

    int myInt = 0;
    Type myType = myInt.GetType();
    var myInstance = new myClass<myType>("myHeader");

在所有示例中,我都收到以下错误:

找不到类型或命名空间名称“myType”(您是否缺少 using 指令或程序集引用?)

我不能直接使用int 的原因是因为我在运行时从特定程序集中加载类型,所以它们不会一直是“int”。

【问题讨论】:

  • 你能把函数变成通用的,然后就做new myClass&lt;T&gt;("myHeader");吗?
  • 感谢 Quantic,这对我也有帮助。

标签: c# .net dynamic types casting


【解决方案1】:

要在运行时创建generic 列表,您必须使用Reflection

int myInt = 0;
Type myType = myInt.GetType();

// make a type of generic list, with the type in myType variable
Type listType = typeof(List<>).MakeGenericType(myType);

// init a new generic list
IList list = (IList) Activator.CreateInstance(listType);

更新 1:

int myInt = 0;
Type myType = myInt.GetType(); 
Type genericClass = typeof(MyClass<>); 
Type constructedClass = genericClass.MakeGenericType(myType); 
String MyParameter = "value"; 
dynamic MyInstance = Activator.CreateInstance(constructedClass, MyParameter);

【讨论】:

  • 感谢阿里,作为补充,完整代码下方:int myInt = 0;键入 myType = myInt.GetType();类型 genericClass = typeof(MyClass);类型ConstructedClass = genericClass.MakeGenericType(myType); String MyParameter = "值";动态 MyInstance = Activator.CreateInstance(constructedClass, MyParameter);问候
  • @m506 不客气。如果您正在寻找答案,请不要忘记接受答案。我更新了帖子并将您的代码放在那里。
猜你喜欢
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 2020-05-11
相关资源
最近更新 更多