在C#中继承,T:new()的含义是什么?

Har*_*9pl 1 c# new-operator

可能重复:
new()是什么意思?

喜欢标题.我想知道代码中的这种语法是什么意思.我在一些样品中找到它,但没有解释,我真的不知道它做了什么.

public class SomeClass<T> where T: new()  // what does it mean?
Run Code Online (Sandbox Code Playgroud)

任何人都能解释一下吗?

Abe*_*bel 6

也许你的意思是你在这些方面看到了什么?

public class SomeClass<T> where T: new() 
{...}
Run Code Online (Sandbox Code Playgroud)

这意味着您只能使用具有公共无参数构造函数的类型T的泛型类.这些被称为泛型类型约束.即,你不能这样做(见CS0310):

// causes CS0310 because XmlWriter cannot be instantiated with paraless ctor
var someClass = new SomeClass<XmlWriter>();

// causes same compile error for same reason
var someClass = new SomeClass<string>();
Run Code Online (Sandbox Code Playgroud)

你为什么需要这样的约束?假设您要实例化一个新的类型变量T.只有在有此约束时才能执行此操作,否则,编译器无法事先知道实例化是否有效.即:

public class SomeClass<T> where T: new() 
{
    public static T CreateNewT()
    {
         // you can only write "new T()" when you also have "where T: new()"
         return new T();
    }
}
Run Code Online (Sandbox Code Playgroud)