new 條件約束 (C# 參考)new constraint (C# Reference)

new 條件約束指定泛型類別宣告中的型別引數都必須有公用無參數建構函式。The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor. 若要使用 new 條件約束,型別不能為抽象。To use the new constraint, the type cannot be abstract.

當泛型類別建立新的型別執行個體時,將 new 條件約束套用至型別參數,如下列範例所示:Apply the new constraint to a type parameter when a generic class creates new instances of the type, as shown in the following example:

class ItemFactory<T> where T : new()
    public T GetNewItem()
        return new T();

當您使用 new() 條件約束與其他條件約束時,它必須是最後一個指定的︰When you use the new() constraint with other constraints, it must be specified last:

public class ItemFactory2<T>
    where T : IComparable, new()
{  }

如需詳細資訊,請參閱型別參數的條件約束For more information, see Constraints on Type Parameters.

您也可以使用 new 關鍵字來建立型別的執行個體或作為成員宣告修飾詞You can also use the new keyword to create an instance of a type or as a member declaration modifier.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格中的型別參數條件約束一節。For more information, see the Type parameter constraints section of the C# language specification.

另請參閱See also