从泛型类继承时,什么时候应该使用 new() 关键字?

pej*_*man 4 c# generics

我读了一篇关于泛型类的培训文章,它有一些这样的代码:

public class ValidationBase {
  public virtual bool IsValidName(string name) {
    return name.Length > 5;
  }
}

 public class LogicBase<T> where T : ValidationBase, new() {
    private T _Validations = default(T);
      public T Validations {
        get {
          if (_Validations == null) {
            _Validations = new T();
           }
        return _Validations;
          }
       set { _Validations = value; }
      }
}
Run Code Online (Sandbox Code Playgroud)

它说:

如果没有为 T 提供特定类型,则 new 关键字默认创建 DataModelBase 类的实例

我真的不明白我们new()什么时候应该使用关键字?

注意:如果像这样编辑上面的代码:

 public class LogicBase<T> where T : ValidationBase
Run Code Online (Sandbox Code Playgroud)

代替

 public class LogicBase<T> where T : ValidationBase, new()
Run Code Online (Sandbox Code Playgroud)

会发生什么?

rhu*_*hes 5

指定泛型类时,new()作为对可能的类型的约束T

在这种情况下,new()表示 的类型T必须是具有公共无参数构造函数的类。

例如:

public class MyGenericClass<T> where T : new()
{
}

public class MyClass
{
    public MyClass()
    {
    }
}

public class MyClass2
{
    public MyClass2(int i)
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        // OK!
        MyGenericClass<MyClass> c1 = new MyGenericClass<MyClass>();

        // Gives the error:
        // 'MyClass2' must be a non-abstract type with a public parameterless
        // constructor in order to use it as parameter 'T' in the generic type
        // or method 'MyGenericClass<T>'
        MyGenericClass<MyClass2> c2 = new MyGenericClass<MyClass2>();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以T使用new T(). 由于这是通用的,所有类型都T必须符合相同的规则。where T: new()强制所有类型T都有一个公共的、无参数的构造函数。

你编码:

if (_Validations == null) {
    _Validations = new T();
}
Run Code Online (Sandbox Code Playgroud)

创建 的新实例T。就像T任何事情一样,T因此必须能够使用new MyType().