DotNet · 2022年4月25日

Office自动化客户端的早期绑定和晚期绑定

使应用程序(如
Microsoft Office 应用程序)自动运行时,对 Office
应用程序对象的属性和方法的调用必须以某种方式连接到这些对象。将属性和方法调用连接到实现这些属性和方法的对象的过程通常称为绑定。在 Visual C# 中,有两种类型的绑定,分别是早期绑定 晚期绑定。所选择的绑定类型可以影响程序的许多方面,包括性能、灵活性和可维护性。

本文介绍并比较了 Visual C#
自动化客户端的早期绑定和晚期绑定,提供了能说明这两类绑定的代码示例。

早期绑定

采用早期绑定时,Visual
C# 使用有关所涉及的 Office
应用程序的可用类型信息直接绑定到它需要使用的方法或属性。编译器可以执行类型和语法检查,以确保传递到方法或属性的参数的数量和类型正确无误,并且返回的值是所期望的类型。由于早期绑定在运行时调用属性或方法所需的工作量较小,因此有时速度较快。然而,虽然早期绑定可能速度较快,但与晚期绑定之间的性能差异通常不大。

早期绑定确实有这样一个小缺点:可能会带来版本兼容性问题。例如,假定诸如
Microsoft Excel 2002 之类的自动化服务器引入了 Excel 2000
中没有的新方法或属性,或者更改了现有的属性或方法。这些更改可能会改变对象的二进制布局,并导致使用 Excel 2002 类型信息实现 Excel 2000
自动化的 Visual C# 应用程序出现问题。为了避免早期绑定发生这样的问题,通常建议您在开发和测试自动化客户端时,使用您希望支持的最低版本的 Office
应用程序的类型信息。

下列步骤说明了如何创建使用早期绑定的自动化客户端。请注意,正如这些步骤所说明的那样,早期绑定要求您引用自动化客户端的类型库。

创建使用早期绑定的自动化客户端

  1. 启动 Microsoft
    Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。从 Visual C# 项目类型中选择 Windows 应用程序。默认情况下会创建 Form1。
  2. 添加对 Microsoft Excel
    对象库
    的引用。为此,请按照下列步骤操作:

    1. 项目菜单上,单击添加引用
    2.  COM 选项卡上,找到 Microsoft Excel 对象库并单击选择

      注意:Office 2003 包含主 Interop 程序集
      (PIA)。Office XP 不包含 PIA,但您可以下载 PIA。 有关 Office XP PIA 的其他信息,请单击下面的文章编号,以查看
      Microsoft 知识库中相应的文章:

      328912  Microsoft Office XP 主 interop 程序集
      (PIA) 可供下载
    3. 添加引用对话框中单击确定以接受您的选择。如果系统提示您为选定的库生成包装,请单击
  3. 视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
  4. 双击 Button1。将出现该窗体的代码窗口。
  5. 在代码窗口中,将以下代码

    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    					

    替换为:

    private void button1_Click(object sender, System.EventArgs e)
    {
    	Excel.Application objApp;
    	Excel._Workbook objBook;
    	Excel.Workbooks objBooks;
    	Excel.Sheets objSheets;
    	Excel._Worksheet objSheet;
    	Excel.Range range;
    
    	try
    	{
    		// Instantiate Excel and start a new workbook.
    		objApp = new Excel.Application();
    		objBooks = objApp.Workbooks;
    		objBook = objBooks.Add( Missing.Value );
    		objSheets = objBook.Worksheets;
    		objSheet = (Excel._Worksheet)objSheets.get_Item(1);
    
    		range = objSheet.get_Range("A1", Missing.Value);
    
    		range.set_Value(Missing.Value, "Hello, World!" );
    
    		//Return control of Excel to the user.
    		objApp.Visible = true;
    		objApp.UserControl = true;
    	}
    	catch( Exception theException ) 
    	{
    		String errorMessage;
    		errorMessage = "Error: ";
    		errorMessage = String.Concat( errorMessage, theException.Message );
    		errorMessage = String.Concat( errorMessage, " Line: " );
    		errorMessage = String.Concat( errorMessage, theException.Source );
    
    		MessageBox.Show( errorMessage, "Error" );
    	}
    }  
    					

  6. 滚动到代码窗口的顶部。将下面的代码行添加到 using 指令列表的末尾:

    using System.Reflection;
    using Excel = Microsoft.Office.Interop.Excel;
    					

晚期绑定

与早期绑定不同,晚期绑定要等到运行时才会将属性和方法调用绑定到它们的对象。为此,目标对象必须实现一个特殊的
COM 接口:IDispatch。利用 IDispatch::GetIDsOfNames 方法,Visual C# 可以询问对象支持哪些方法和属性,然后,IDispatch::Invoke 方法允许 Visual C#
调用这些方法和属性。这种晚期绑定的优点是:它消除了早期绑定所固有的某些版本依赖性。然而,它也有以下缺点:省略了对自动化代码完整性的编译时检查,也不提供“智能感知”功能(该功能可提供有助于正确调用方法和属性的提示)。

要在 Visual C# 中使用晚期绑定,请使用 System.Type.InvokeMember 方法。此方法调用IDispatch::GetIDsOfNames  IDispatch::Invoke 来绑定到自动化服务器的方法和属性。

创建使用晚期绑定的自动化客户端

  1. 启动 Microsoft
    Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。从 Visual C# 项目类型中选择 Windows 应用程序。默认情况下会创建 Form1。
  2. 视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
  3. 双击 Button1。将出现该窗体的代码窗口。
  4. 在代码窗口中,将以下代码

    private void button1_Click(object sender, System.EventArgs e)
    {
    }
    						

    替换为:

    private void button1_Click(object sender, System.EventArgs e)
    {
    	object objApp_Late;
    	object objBook_Late;
    	object objBooks_Late;
    	object objSheets_Late;
    	object objSheet_Late;
    	object objRange_Late;
    	object[] Parameters;
    
    	try
    	{
    		// Get the class type and instantiate Excel.
    		Type objClassType; 
    		objClassType = Type.GetTypeFromProgID("Excel.Application"); 
    		objApp_Late = Activator.CreateInstance(objClassType);
    
    		//Get the workbooks collection.
    		objBooks_Late = objApp_Late.GetType().InvokeMember( "Workbooks", 
    		BindingFlags.GetProperty, null, objApp_Late, null );
    
    		//Add a new workbook.
    		objBook_Late = objBooks_Late.GetType().InvokeMember( "Add", 
    			BindingFlags.InvokeMethod, null, objBooks_Late, null );
    
    		//Get the worksheets collection.
    		objSheets_Late = objBook_Late.GetType().InvokeMember( "Worksheets",
    			BindingFlags.GetProperty, null, objBook_Late, null );
    
    		//Get the first worksheet.
    		Parameters = new Object[1];
    		Parameters[0] = 1;
    		objSheet_Late = objSheets_Late.GetType().InvokeMember( "Item", 
    			BindingFlags.GetProperty, null, objSheets_Late, Parameters );
    
    		//Get a range object that contains cell A1.
    		Parameters = new Object[2];
    		Parameters[0] = "A1";
    		Parameters[1] = Missing.Value;
    		objRange_Late = objSheet_Late.GetType().InvokeMember( "Range",
    			BindingFlags.GetProperty, null, objSheet_Late, Parameters );
    
    		//Write "Hello, World!" in cell A1.
    		Parameters = new Object[1];
    		Parameters[0] = "Hello, World!";
    		objRange_Late.GetType().InvokeMember( "Value", BindingFlags.SetProperty, 
    			null, objRange_Late, Parameters );
    
    		//Return control of Excel to the user.
    		Parameters = new Object[1];
    		Parameters[0] = true;
    		objApp_Late.GetType().InvokeMember( "Visible", BindingFlags.SetProperty,
    			null, objApp_Late, Parameters );
    		objApp_Late.GetType().InvokeMember( "UserControl", BindingFlags.SetProperty,
    			null, objApp_Late, Parameters );
    	}
    	catch( Exception theException ) 
    	{
    		String errorMessage;
    		errorMessage = "Error: ";
    		errorMessage = String.Concat( errorMessage, theException.Message );
    		errorMessage = String.Concat( errorMessage, " Line: " );
    		errorMessage = String.Concat( errorMessage, theException.Source );
    
    		MessageBox.Show( errorMessage, "Error" );
    	}
    }
    					

  5. 滚动到代码窗口的顶部。将下面的代码行添加到 using 指令列表的末尾:

    using System.Reflection;