[英]Building a generic Object with a type parameter determined 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;
}
所有对象都具有相同的父ParentClass
//This is what i want to do or something like this
public void SomeFunction(Type someType)
{
ParentClass newObj = GetInstance<someType>();
}
//////通过以下注释解决
private ParentClass GetElement(Type theType)
{
ParentClass item = (ParentClass)SomeClass.Instance.GetItem(theType);
if (item == null)
{
item = (ParentClass)Activator.CreateInstance(theType);
}
return item;
}
和类SomeClass.Instance.GetItem()中的方法; 不再使用泛型类型使用对象,现在将类型作为参数
ParentClass newObj = (ParentClass)Activator.CreateInstance(type)
从MSDN
Activator.CreateInstance
>使用该类型的默认构造函数创建指定类型的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.