开发者

Instantiate Generic Type in C# class [duplicate]

This question already has answers here: In C#, how to instantiate a passed generic type inside a method? (8 answers) Close开发者_开发问答d 9 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜