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.
// 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
//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(); to dont use generic type use object all and now the Type is pased as parameter
ParentClass newObj = (ParentClass)Activator.CreateInstance(type)
From MSDN
Activator.CreateInstance
-> Creates an instance of the specified type using that type's default constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.