介绍用于 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
关键字还用于类型参数列表,以指定所提供的类型必须公开可访问的无参数构造函数。 有关类型参数和约束的详细信息,请参阅 类型列表。
若要为类创建构造函数过程,请将过程的名称 Sub
设置为 New
关键字。 有关详细信息,请参阅 对象生存期:如何创建和销毁对象。
关键字 New
可用于以下上下文: