Instantiate Generic Type in C# class [duplicate]
Pretty basic question in C#,
class Data<T>
{
T obj;
public Data()
{
// Allocate to obj from T here
// Some Activator.CreateInstance() method ?
obj = ???
}
}
How do i do this?
If you want to create your own instance of T, then you need define a constraint new()
class Data<T> where T: new()
{
T obj;
public Data()
{
obj = new T();
}
}
If you want to pass in the obj then you need to allow it in the constructor
class Data<T>
{
T obj;
public Data(T val)
{
obj = val;
}
}
YOU can use the new
constraint in your generic class definition to ensure T has a default constructor you can call. Constraints allow you to inform the compiler about certain behaviors (capabilities) that the generic parameter T must adhere to.
class Data<T> where T : new()
{
T obj;
public Data()
{
obj = new T();
}
}
this may help: http://pooyakhamooshi.blogspot.com/2011/06/how-to-instantiate-generic-type-with.html
精彩评论