Share via


New 運算子 (Visual Basic)

引進 New 子句,以建立新的物件執行個體、指定型別參數上的建構函式條件約束,或識別做為類別建構函式的 Sub 程序。

備註

在宣告或指派陳述式中,New 子句必須指定可建立執行個體的定義類別。 這表示類別必須公開一個或多個建構函式,以供呼叫程式碼存取。

您可以在宣告陳述式 (Declaration Statement) 或指派陳述式中使用 New 子句。 當陳述式執行時,會呼叫指定類別的適當建構函式,並傳遞任何您所提供的引數。 下列範例會建立 Customer 類別的執行個體,其具有兩個建構函式,一個不採用參數,另一個採用字串參數,用以說明。

' 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 可建立新的陣列執行個體,如以下範例所示。

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}

若記憶體不足,無法產生新的執行個體時,Common Language Runtime (CLR) 會擲回 OutOfMemoryException 錯誤。

注意事項注意事項

New 關鍵字也可用在型別參數清單中,指定提供的型別必須公開可存取的無參數建構函式。 如需型別參數和條件約束的詳細資訊,請參閱型別清單 (Visual Basic)

若要建立類別的建構函式程序,請將 Sub 程序的名稱設定為 New關鍵字。 如需詳細資訊,請參閱物件存留期:物件的建立和終結 (Visual Basic)

New 關鍵字可用於以下內容中:

Dim 陳述式 (Visual Basic)

Of 子句 (Visual Basic)

Sub 陳述式 (Visual Basic)

請參閱

參考

型別清單 (Visual Basic)

OutOfMemoryException

概念

Visual Basic 中的泛型型別 (Visual Basic)

物件存留期:物件的建立和終結 (Visual Basic)

其他資源

關鍵字 (Visual Basic)