正常的声明语句用于声明对象变量。 对于数据类型,您指定Object(即Object Data Type) 或更具体的类是要创建该对象。
声明一个变量,作为Object等同于其声明为xref:System.Object?displayProperty=nameWithType。
具有特定的对象类的变量声明时,它可以访问所有方法和属性公开的类和它所继承的类。 如果声明的变量xref:System.Object,它可以访问的成员xref:System.Object类,除非您启用Option Strict Off允许后期绑定。
声明语法
使用以下语法声明对象变量:
Dim variablename As [New] { objectclass | Object }
此外可以指定公共,受保护,友元, Protected Friend,专用,共享,或静态声明中。 以下示例声明是有效的:
Private objA As Object
Static objB As System.Windows.Forms.Label
Dim objC As System.OperatingSystem
后期绑定和早期绑定
有时特定类是未知的代码运行之前。 在这种情况下,您必须声明对象变量与Object数据类型。 这将创建的常规引用到任何类型的对象,并在运行时分配特定的类。 这称为后期绑定。 后期绑定需要额外的执行时间。 它也会限制你的代码的方法和类,最近已向其分配的属性。 如果你的代码尝试访问不同类的成员,这可能导致运行时错误。
当在编译时知道特定的类时,应将声明为该类的对象变量。 这称为早期绑定。 早期绑定可以提高性能,并保证您对所有方法和属性的特定类的代码访问权限。 在前面的示例声明中,如果变量objA使用仅类的对象xref:System.Windows.Forms.Label?displayProperty=nameWithType,则应指定As System.Windows.Forms.Label其声明中。
早期绑定的优点
声明对象变量作为特定类具有几个优势:
-
自动类型检查
-
保证特定类的所有成员访问
-
在代码编辑器中的 Microsoft IntelliSense 支持
-
改进了的代码的可读性
-
在代码中减少错误
-
在捕获到错误编译时间而不是运行时
-
更快地执行代码
对象变量的成员的访问权限
当Option Strict打开On,对象变量可以访问的方法和类与其声明的属性。 下面的示例阐释了这一点。
' Option statements must precede all other source file lines.
Option Strict On
' Imports statement must precede all declarations in the source file.
Imports System.Windows.Forms
Public Sub accessMembers()
Dim p As Object
Dim q As System.Windows.Forms.Label
p = New System.Windows.Forms.Label
q = New System.Windows.Forms.Label
Dim j, k As Integer
' The following statement generates a compiler ERROR.
j = p.Left
' The following statement retrieves the left edge of the label in pixels.
k = q.Left
End Sub
在此示例中, p 仅可使用 xref:System.Object 类的成员,这不包括 Left 属性。 另一方面, q 已声明为 xref:System.Windows.Forms.Label类型,因此它可以使用 xref:System.Windows.Forms.Label 命名空间中 xref:System.Windows.Forms 类的所有方法和属性。
对象变量的灵活性
使用继承层次结构中的对象,可以用来声明对象变量的类的选择。 在进行选择时,必须平衡的一个类成员访问对象赋值的灵活性。 例如,考虑到会导致在继承层次结构xref:System.Windows.Forms.Form?displayProperty=nameWithType类:
xref:System.MarshalByRefObject
xref:System.ComponentModel.Component
xref:System.Windows.Forms.Control
xref:System.Windows.Forms.ScrollableControl
xref:System.Windows.Forms.ContainerControl
xref:System.Windows.Forms.Form
假设你的应用程序定义一个名为的窗体类specialForm,后者又继承类xref:System.Windows.Forms.Form。 你可以专门引用对象变量声明specialForm,如下面的示例所示。
Public Class specialForm
Inherits System.Windows.Forms.Form
' Insert code defining methods and properties of specialForm.
End Class
Dim nextForm As New specialForm
在前面的示例中的声明限制在变量nextForm到类的对象specialForm,但这也使得所有的方法和属性的specialForm供nextForm,以及从其的所有类的所有成员specialForm继承。
可以通过声明它的类型进行更一般的对象变量xref:System.Windows.Forms.Form,如下面的示例所示。
Dim anyForm As System.Windows.Forms.Form
在前面的示例中的声明,可在分配到应用程序中的任何窗体anyForm。 但是,尽管anyForm可以访问的类的所有成员xref:System.Windows.Forms.Form,它不能使用任何其他方法或属性,例如为特定窗体定义specialForm。
基类的所有成员都都可用于派生类,但派生类的其他成员都将不可用到的基类。
请参阅
历史资料。此文对应 2019-08-18 的中文文档快照,适用产品版本和命令行为以原文为准。
来源与署名:Microsoft 和文档贡献者。固定版本原文。文档采用 CC BY 4.0,示例代码采用 MIT 授权。本站将 Markdown 转为 HTML,规范化链接,移除外部媒体和导航标记。
