Given the class :
public class MyObject
{We can instantiate a new MyObject object by :
public string Name { get; set; }
}
var newObject = (MyObject)Activator.CreateInstance(typeof(MyObject));
What happens if the class looks like :
public class DataObject<T>We can achieve this goal with :
{
public DataObject(string name)
{
Name = name;
}
public string Name { get; set; }
public List<T> ContenList { get; set; }
}
var dataObjectBody = (DataObject<string>)Activator.CreateInstance(typeof(DataObject<>).MakeGenericType(typeof(string)),"Foody");The MakeGenericType tells that we want to use the generic T as a string type.
The "Foody" value is used for the constructor name parameter when the Activator.CreateInstance creates the object at runtime.
In the case where the class uses a multi generic type like:
public class DataObject1<T,TU>The same method is being used, we need to do small changes on the arguments
{
public DataObject1(string name)
{
Name = name;
}
public string Name { get; set; }
public List<T> ContenListT { get; set; }
public List<TU> ContenListU { get; set; }
}
var obj1 =
(DataObject1<string, string>)
Activator.CreateInstance(typeof (DataObject1<,>).MakeGenericType(typeof (string), typeof (string)),
"Foody");
No comments:
Post a Comment