11

C#中非常基本的问题,

class Data<T>
 {
    T obj;

    public Data()
    {
      // Allocate to obj from T here
      // Some Activator.CreateInstance() method ?
      obj =  ???
    }
 }

我该怎么做呢?

4

3 回答 3

23

如果要创建自己的 T 实例,则需要定义约束new()

class Data<T> where T: new()
 {
    T obj;

    public Data()
    {
      obj =  new T();
    }
 }

如果你想传入 obj 那么你需要在构造函数中允许它

 class Data<T>
     {
        T obj;

        public Data(T val)
        {
          obj = val;
        }
     }
于 2010-01-07T23:03:02.507 回答
1

您可以在泛型类定义中使用new约束来确保 T 具有可以调用的默认构造函数。约束允许您通知编译器泛型参数 T 必须遵守的某些行为(功能)。

class Data<T> where T : new()
{
    T obj;

    public Data()
    {
        obj = new T();
    }
}
于 2010-01-07T23:03:53.100 回答
0

这可能会有所帮助: http: //pooyakhamooshi.blogspot.com/2011/06/how-to-instantiate-generic-type-with.html

于 2011-06-17T21:27:22.310 回答