New 运算符 (Visual Basic)New Operator (Visual Basic)

引入 New 子句来创建新的对象实例,指定类型参数上的构造函数约束,或将 Sub 过程标识为类构造函数。Introduces a New clause to create a new object instance, specifies a constructor constraint on a type parameter, or identifies a Sub procedure as a class constructor.

备注Remarks

在声明或赋值语句中,New 子句必须指定一个已定义的类,可从中创建实例。In a declaration or assignment statement, a New clause must specify a defined class from which the instance can be created. 这意味着,该类必须公开调用代码可以访问的一个或多个构造函数。This means that the class must expose one or more constructors that the calling code can access.

可在声明语句或赋值语句中使用 New 子句。You can use a New clause in a declaration statement or an assignment statement. 当语句运行时,它将调用指定类的适当构造函数,同时传递您提供的任何自变量。When the statement runs, it calls the appropriate constructor of the specified class, passing any arguments you have supplied. 下面的示例通过创建一个 Customer 类的实例,该实例具有两个构造函数,一个不采用参数,另一个采用字符串参数,如下所示:The following example demonstrates this by creating instances of a Customer class that has two constructors, one that takes no parameters and one that takes a string parameter:

' 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 可以创建一个新的数组实例,如以下示例中所示:Since arrays are classes, New can create a new array instance, as shown in the following example:

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 错误。The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the new instance.

备注

还可以在类型参数列表中使用 New 关键字,以指定提供的类型必须公开可访问的无参数构造函数。The New keyword is also used in type parameter lists to specify that the supplied type must expose an accessible parameterless constructor. 有关类型参数和约束的详细信息,请参阅Type ListFor more information about type parameters and constraints, see Type List.

若要为类创建构造函数过程,请将 Sub 过程的名称设置为 New 关键字。To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword. 有关详细信息,请参阅对象生存期:如何创建和销毁对象For more information, see Object Lifetime: How Objects Are Created and Destroyed.

New 关键字可用于以下上下文中:The New keyword can be used in these contexts:

另请参阅See also