vb.net 变量声明什么是最佳实践

use*_*103 4 vb.net visual-studio

在 vb.net 中声明对象实例的最佳实践是什么?

Dim Person1 as Person = new Person()

或者

Dim Person1 as new Person()

Ste*_*art 5

两者没有区别。在 C# 中,没有等效的As New语法,因此您经常会看到 C# 程序员出于无知或只是出于熟悉而选择第一个选项。

但是,有时需要指定类型,例如,如果要将变量键入为接口或基类:

Dim person1 As IPerson = New Person()
Run Code Online (Sandbox Code Playgroud)

或者

Dim person1 As PersonBase = New Student()
Run Code Online (Sandbox Code Playgroud)

还值得一提的是As New,VB6 中存在该语法,但它的含义略有不同。在 .NET 中,As New设置变量的起始值。在 VB6 中,它使变量“自动实例化”。在 VB6 中,如果你声明了一个变量As New,它会在你每次使用该变量时自动实例化一个新对象,当它等于 时Nothing。例如:

'This is VB6, not VB.NET
Dim person1 As New Person
MsgBox person1.Name  ' person1 is set to a new Person object because it is currently Nothing
Set person1 = Nothing
MsgBox person1.Name  ' person1 is set to a second new Person object because it is currently Nothing
Run Code Online (Sandbox Code Playgroud)

在 VB.NET 中,它不会这样做。在 VB.NET 中,如果您将变量设置为Nothing,它将保持这种状态,直到您将其设置为其他内容,例如:

'This is VB.NET
Dim person1 As New Person()  ' person1 is immediately set to a new Person object
MessageBox.Show(person1.Name)
person1 = Nothing
MessageBox.Show(person1.Name)   ' Throws an exception because person1 is Nothing
Run Code Online (Sandbox Code Playgroud)

  • 关于接口/抽象类的好点。 (3认同)