早期绑定和晚期绑定

来源:互联网 发布:2016的天干地支的算法 编辑:程序博客网 时间:2024/04/27 19:35

当对象分配给对象变量时,Visual   Basic   编译器执行名为“绑定”的进程。当对象分配给声明为特定对象类型的变量时,该对象为“早期绑定”。早期绑定对象允许编译器在应用程序执行前分配内存以及执行其他优化。例如,下面的代码段声明了一个   FileStream   类型的变量:  
   
  '   Add   Imports   statements   to   the   top   of   your   file.  
  Imports   System.IO  
  '...  
  '     Create   a   variable   to   hold   a   new   object.  
        Dim   FS   As   FileStream  
      '   Assign   a   new   object   to   the   variable.  
        FS   =   New   FileStream("C:/tmp.txt",   FileMode.Open)  
  因为   FileStream   是一种特定的对象类型,所以分配给   FS   的实例是早期绑定。  
   
  与之相对,当对象分配给声明为   Object   类型的变量时,该对象为“晚期绑定”。这种类型的对象可以保存对任何对象的引用,但没有早期绑定对象的很多优越性。例如,下面的代码段声明一个对象变量来保存由   CreateObject   函数返回的对象:  
   
  '   To   use   this   example,   you   must   have   Microsoft   Excel   installed   on   your   computer.  
  Option   Strict   Off   '   Option   Strict   Off   allows   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()  
        xlSheet.Application.Visible   =   True   '   Show   the   application.  
        '   Place   some   text   in   the   second   row   of   the   sheet.  
        xlSheet.Cells(2,   2)   =   "This   is   column   B   row   2"  
  End   Sub  
  应当尽可能使用早期绑定对象,因为它们允许编译器进行重要优化,从而生成更高效的应用程序。早期绑定对象比晚期绑定对象快很多,并且能通过确切声明所用的对象种类使代码更易于阅读和维护。早期绑定的另一个优越性在于它启用有用的功能(如自动代码完成和动态帮助),因为   Visual   Studio   .NET   集成开发环境   (IDE)   可以在您编辑代码时准确确定正在使用的对象类型。由于早期绑定使编译器可以在编译程序时报告错误,所以它减小了运行时错误的数量和严重度。  
   
  注意       晚期绑定只能用于访问声明为   Public   的类型成员。访问声明为   Friend   或   Protected   Friend   的成员将会导致运行时错误。   
 

原创粉丝点击