可能是重复问题:
new()是什么意思?
就像标题所示。我想知道代码中这个语法的含义。我在一些示例中找到了它,但没有解释,我真的不知道它是做什么的。
public class SomeClass<T> where T: new() // what does it mean?
有人能为我解释一下吗?
可能是重复问题:
new()是什么意思?
就像标题所示。我想知道代码中这个语法的含义。我在一些示例中找到了它,但没有解释,我真的不知道它是做什么的。
public class SomeClass<T> where T: new() // what does it mean?
public class SomeClass<T> where T: new()
{...}
这意味着您只能使用具有公共无参数构造函数的类型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>();
为什么需要这样的限制?假设您想实例化类型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();
}
}
new SomeClass<string>()
会导致错误(它不会“抛出”),因为string
没有无参构造函数。 - svick