New 運算子 (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 關鍵字可用於以下內容:

另請參閱