在 vb.net 中声明对象实例的最佳实践是什么?
将 Person1 调暗为 Person = new Person()
或
将 Person1 调暗为新人()
两者之间没有区别。 在 C# 中,没有等效的语法As New
,因此您经常会看到 C# 程序员出于无知或只是出于熟悉而选择第一个选项。
但是,有时需要指定类型,例如,如果要将变量键入为接口或基类:
Dim person1 As IPerson = New Person()
或
Dim person1 As PersonBase = New Student()
还值得一提的是,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
在 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