new 運算子 (C# 參考)new operator (C# reference)

new 運算子會建立型別的新執行個體。The new operator creates a new instance of a type.

您也可以使用 new 關鍵字作為成員宣告修飾詞泛型型別條件約束You can also use the new keyword as a member declaration modifier or a generic type constraint.

建構函式引動過程Constructor invocation

若要建立型別的新執行個體,您通常會使用 new 運算子叫用該型別的其中一個建構函式To create a new instance of a type, you typically invoke one of the constructors of that type using the new operator:

var dict = new Dictionary<string, int>();
dict["first"] = 10;
dict["second"] = 20;
dict["third"] = 30;

Console.WriteLine(string.Join("; ", dict.Select(entry => $"{entry.Key}: {entry.Value}")));
// Output:
// first: 10; second: 20; third: 30

您可以搭配 new 運算子使用物件或集合初始設定式,來在單一陳述式中具現化和初始化物件,如下列範例所示:You can use an object or collection initializer with the new operator to instantiate and initialize an object in one statement, as the following example shows:

var dict = new Dictionary<string, int>
    ["first"] = 10,
    ["second"] = 20,
    ["third"] = 30

Console.WriteLine(string.Join("; ", dict.Select(entry => $"{entry.Key}: {entry.Value}")));
// Output:
// first: 10; second: 20; third: 30

從 c # 9.0 開始,函式調用運算式是目標型別。Beginning with C# 9.0, constructor invocation expressions are target-typed. 也就是說,如果已知運算式的目標型別,您可以省略型別名稱,如下列範例所示:That is, if a target type of an expression is known, you can omit a type name, as the following example shows:

List<int> xs = new();
List<int> ys = new(capacity: 10_000);
List<int> zs = new() { Capacity = 20_000 };

Dictionary<int, List<int>> lookup = new()
    [1] = new() { 1, 2, 3 },
    [2] = new() { 5, 8, 3 },
    [5] = new() { 1, 0, 4 }

如先前的範例所示,您一律使用目標型別運算式中的括弧 newAs the preceding example shows, you always use parentheses in a target-typed new expression.

如果運算式的目標型別 new 未知 (例如,當您使用 var 關鍵字) 時,必須指定型別名稱。If a target type of a new expression is unknown (for example, when you use the var keyword), you must specify a type name.

建立陣列Array creation

您也可以使用 new 運算子建立陣列執行個體,如下列範例所示:You also use the new operator to create an array instance, as the following example shows:

var numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

Console.WriteLine(string.Join(", ", numbers));
// Output:
// 10, 20, 30

在單一陳述式中使用陣列初始化語法建立陣列執行個體,並使用項目。Use array initialization syntax to create an array instance and populate it with elements in one statement. 下列範例會示範執行該操作的各種方式:The following example shows various ways how you can do that:

var a = new int[3] { 10, 20, 30 };
var b = new int[] { 10, 20, 30 };
var c = new[] { 10, 20, 30 };
Console.WriteLine(c.GetType());  // output: System.Int32[]

如需陣列的詳細資訊,請參閱陣列For more information about arrays, see Arrays.

匿名型別的具現化Instantiation of anonymous types

若要建立匿名型別的執行個體,請使用 new 運算子及物件初始設定式語法:To create an instance of an anonymous type, use the new operator and object initializer syntax:

var example = new { Greeting = "Hello", Name = "World" };
Console.WriteLine($"{example.Greeting}, {example.Name}!");
// Output:
// Hello, World!

型別執行個體的解構Destruction of type instances

您不需要終結先前建立的型別執行個體。You don't have to destroy earlier created type instances. 參考和實值型別的執行個體都會自動終結。Instances of both reference and value types are destroyed automatically. 實值型別的執行個體會在內容包含它們時立即終結。Instances of value types are destroyed as soon as the context that contains them is destroyed. 在移除參考型別的最後一個參考之後,垃圾收集行程會將這些實例被 垃圾收集 行程終結。Instances of reference types are destroyed by the garbage collector at some unspecified time after the last reference to them is removed.

針對包含非受控資源的類型實例(例如,檔案控制代碼),建議採用具決定性的清除,以確保其所包含的資源會儘快釋出。For type instances that contain unmanaged resources, for example, a file handle, it's recommended to employ deterministic clean-up to ensure that the resources they contain are released as soon as possible. 如需詳細資訊,請參閱 System.IDisposable API 參考和 using 陳述式一文。For more information, see the System.IDisposable API reference and the using statement article.

運算子是否可多載Operator overloadability

使用者定義型別不可多載 new 運算子。A user-defined type cannot overload the new operator.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格new 運算子一節。For more information, see The new operator section of the C# language specification.

如需目標型別運算式的詳細資訊 new ,請參閱 功能提案注意事項For more information about a target-typed new expression, see the feature proposal note.

另請參閱See also