什么意味着S:在c#中的new()

use*_*871 9 c# generics

在下面的代码中,我不知道"where S:new()"部分是什么意思.在Google中查找更多信息的关键字是什么?

    public virtual void Print<S, T>() 
        where S : new() 
    { 
        Console.WriteLine(default(T)); 
        Console.WriteLine(default(S)); 
    } 
Run Code Online (Sandbox Code Playgroud)

Cha*_*ion 16

该new()约束是指特定的泛型参数需要有一个默认的构造函数(即不带参数的构造函数).

这样做的目的通常是允许您键入 - 安全地构造泛型参数类型的新实例,而无需求助于Reflection/Activator.CreateInstance.

例如:

public T Create<T>() where T : new()
{
    // allowed because of the new() constraint
    return new T();
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看http://msdn.microsoft.com/en-us/library/sd2w2ew5%28v=vs.80%29.aspx.

至于谷歌搜索术语,我会尝试"c#new()约束".