Visual Basic 编译器执行在将对象分配给对象变量时调用 binding
的进程。 将对象分配给声明为特定对象类型的变量时,会 提前绑定 该对象。 早期绑定对象允许编译器在应用程序执行之前分配内存并执行其他优化。 例如,以下代码片段声明一个变量的类型 FileStream:
' Create a variable to hold a new object.
Dim FS As System.IO.FileStream
' Assign a new object to the variable.
FS = New System.IO.FileStream("C:\tmp.txt",
System.IO.FileMode.Open)
由于 FileStream 是特定的对象类型,因此 FS
分配给的实例是提前绑定的。
相反,如果对象被分配给声明为 类型的变量,就是Object
对象。 此类型的对象可以保留对任何对象的引用,但缺少早期绑定对象的许多优点。 例如,以下代码片段声明一个对象变量以保存函数返回 CreateObject
的对象:
' To use this example, you must have Microsoft Excel installed on your computer.
' Compile with Option Strict Off to allow late binding.
Sub TestLateBinding()
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
xlApp = CreateObject("Excel.Application")
' Late bind an instance of an Excel workbook.
xlBook = xlApp.Workbooks.Add
' Late bind an instance of an Excel worksheet.
xlSheet = xlBook.Worksheets(1)
xlSheet.Activate()
' Show the application.
xlSheet.Application.Visible = True
' Place some text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
End Sub
早期绑定的优点
应尽可能使用早期绑定对象,因为它们允许编译器进行重要的优化,从而产生更高效的应用程序。 早期绑定对象比后期绑定对象要快得多,通过准确说明正在使用的对象类型,使代码更易于读取和维护。 早期绑定的另一个优点是,它可实现有用的功能,如自动代码完成和动态帮助,因为 Visual Studio 集成开发环境(IDE)可以确切地确定在编辑代码时使用的对象类型。 早期绑定减少了运行时错误的数量和严重性,因为它允许编译器在编译程序时报告错误。
注释
后期绑定只能用于访问声明为 Public
的类型成员。 访问声明为 Friend
或 Protected Friend
的成员会导致运行时错误。