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}

如果内存不足,无法创建新的实例,公共语言运行时 (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)