New 運算子 (Visual Basic)New Operator (Visual Basic)

引進子句來建立新的物件實例、在型別參數上指定一個函式條件約束, 或Sub將程式識別為類別的方法。 NewIntroduces a New clause to create a new object instance, specifies a constructor constraint on a type parameter, or identifies a Sub procedure as a class constructor.

備註Remarks

在宣告或指派語句中, New子句必須指定可從中建立實例的已定義類別。In a declaration or assignment statement, a New clause must specify a defined class from which the instance can be created. 這表示類別必須公開呼叫程式碼可以存取的一個或多個函式。This means that the class must expose one or more constructors that the calling code can access.

您可以在宣告New語句或指派語句中使用子句。You can use a New clause in a declaration statement or an assignment statement. 當語句執行時, 它會呼叫指定類別的適當的函式, 並傳遞您所提供的任何引數。When the statement runs, it calls the appropriate constructor of the specified class, passing any arguments you have supplied. 下列範例會藉由建立具有兩個函Customer式的類別實例 (不接受任何參數, 另一個採用字串參數) 來示範。The following example demonstrates this by creating instances of a Customer class that has two constructors, one that takes no parameters and one that takes a string parameter.

' For customer1, call the constructor that takes no arguments.
Dim customer1 As New Customer()

' For customer2, call the constructor that takes the name of the 
' customer as an argument.
Dim customer2 As New Customer("Blue Yonder Airlines")

' For customer3, declare an instance of Customer in the first line 
' and instantiate it in the second.
Dim customer3 As Customer
customer3 = New Customer()

' With Option Infer set to On, the following declaration declares
' and instantiates a new instance of Customer.
Dim customer4 = New Customer("Coho Winery")

由於陣列是類別, New因此可以建立新的陣列實例, 如下列範例所示。Since arrays are classes, New can create a new array instance, as shown in the following examples.

Dim intArray1() As Integer
intArray1 = New Integer() {1, 2, 3, 4}

Dim intArray2() As Integer = {5, 6}

' The following example requires that Option Infer be set to On.
Dim intArray3() = New Integer() {6, 7, 8}

如果記憶體不足, 無法建立新的實例OutOfMemoryException , 則 common language runtime (CLR) 會擲回錯誤。The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the new instance.

注意

New關鍵字也會用於型別參數清單中, 以指定提供的型別必須公開可存取的無參數函數。The New keyword is also used in type parameter lists to specify that the supplied type must expose an accessible parameterless constructor. 如需型別參數和條件約束的詳細資訊, 請參閱Type ListFor more information about type parameters and constraints, see Type List.

若要建立類別的Sub方法, 請將程式的名稱設定New為關鍵字。To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword. 如需詳細資訊, 請參閱物件存留期:如何建立和終結物件。For more information, see Object Lifetime: How Objects Are Created and Destroyed.

New 關鍵字可用於以下內容:The New keyword can be used in these contexts:

Dim 陳述式Dim Statement

OfOf

Sub 陳述式Sub Statement

另請參閱See also