这个问题在这里已经有了答案:
VB.Net variable declaration : type or not to type?
(5 个回答)
8年前关闭。
在 vb.net 中声明对象实例的最佳实践是什么?
将 Person1 调暗为 Person = new Person()
或者
将 Person1 调暗为 new Person()
最佳答案
两者没有区别。在 C# 中,没有等价于 As New
语法,所以你经常会看到 C# 程序员出于无知或仅仅出于熟悉而选择第一个选项。
但是,有时需要指定类型,例如,如果要将变量键入为接口(interface)或基类:
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
关于vb.net 变量声明什么是最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861902/