共用方式為


新增運算符 (Visual Basic)

New引進 子句來建立新的物件實例、指定類型參數的建構函式條件約束,或將程序識別Sub為類別建構函式。

備註

在宣告或指派語句中, New 子句必須指定可以建立實例的已定義類別。 這表示 類別必須公開呼叫程式代碼可以存取的一或多個建構函式。

您可以在宣告語句或指派語句中使用 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 也用於類型參數清單中,以指定提供的型別必須公開可存取的無參數建構函式。 如需類型參數和條件約束的詳細資訊,請參閱 類型清單

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

New關鍵字可用於下列內容:

另請參閱