在下面的代码中,我不知道 "where S : new()" 的含义是什么。有什么关键字可以在Google中查找更多信息吗?
public virtual void Print<S, T>()
where S : new()
{
Console.WriteLine(default(T));
Console.WriteLine(default(S));
}
new()
约束表示特定泛型参数需要具有默认构造函数(即没有参数的构造函数)。
通常,这样做是为了让您在不使用反射/Activator.CreateInstance的情况下,安全地构造泛型参数类型的新实例。
例如:
public T Create<T>() where T : new()
{
// allowed because of the new() constraint
return new T();
}
更多信息请查看http://msdn.microsoft.com/en-us/library/sd2w2ew5%28v=vs.80%29.aspx。
至于Google搜索词,我建议尝试“c# new()约束”。
new T();
不会调用真实的实例构造函数;它构造与值类型相同的值,如default(T)
。因此,不允许结合值类型约束和构造函数约束,因此这是非法的:where T : struct, new()
(被认为是多余的)。如果T是引用类型,则default(T)
给出一个空引用,而new T();
调用一个真正的构造函数。 - Jeppe Stig Nielsenpublic
**零参数实例构造函数。(抽象类不应该有public
构造函数。) - Jeppe Stig Nielsen
where T : new()
的问题What does new() do inwhere T : new()
。 - Raymond Chen