简体   繁体   English

使用运行时确定的类型参数构建通用对象

[英]Building a generic Object with a type parameter determined at runtime

i Have the folowing Code and i call this by the function, buy i need to call it fom a Type otherType dynamic at runtime. 我有以下代码,我通过函数调用此代码,购买时我需要在运行时将它称为动态其他类型的Type。

// this in code this works fine
DooClass newOne = GetInstance<DooClass>();

// The function
private T GetInstance<T>() where T : new()
{
    T item = SomeClass.Instance.GetItem<T>();
    if (item == null)
    {
       item = new T();
    }
    return item;
}

All the objects Have the same Parent ParentClass 所有对象都具有相同的父ParentClass

//This is what i want to do or something like this
public void SomeFunction(Type someType)
{
   ParentClass newObj = GetInstance<someType>();
}

/////Solved using comment below by this //////通过以下注释解决

private ParentClass GetElement(Type theType)
{
   ParentClass item = (ParentClass)SomeClass.Instance.GetItem(theType);
   if (item == null)
   {
      item = (ParentClass)Activator.CreateInstance(theType);
   }
   return item;
}

and the metod in the class SomeClass.Instance.GetItem(); 和类SomeClass.Instance.GetItem()中的方法; to dont use generic type use object all and now the Type is pased as parameter 不再使用泛型类型使用对象,现在将类型作为参数

Try Activator.CreateInstance 试试Activator.CreateInstance

  ParentClass newObj = (ParentClass)Activator.CreateInstance(type)

From MSDN MSDN

Activator.CreateInstance -> Creates an instance of the specified type using that type's default constructor. Activator.CreateInstance >使用该类型的默认构造函数创建指定类型的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM