C#.NET绑定Office晚期绑定

与早期绑定不同,C#.NET绑定Office晚期绑定要等到运行时才会将属性和方法调用绑定到它们的对象。为此,目标对象必须实现一个特殊的 COM 接口:IDispatch。利用 IDispatch::GetIDsOfNames 方法,Visual C# 可以询问对象支持哪些方法和属性,然后,IDispatch::Invoke 方法允许 Visual C# 调用这些方法和属性。这种晚期绑定的优点是:它消除了早期绑定所固有的某些版本依赖性。然而,它也有以下缺点:省略了对自动化代码完整性的编译时检查,也不提供“智能感知”功能(该功能可提供有助于正确调用方法和属性的提示)。
要在 Visual C# 中使用C#.NET绑定Office晚期绑定,请使用 System.Type.InvokeMember 方法。此方法调用 IDispatch::GetIDsOfNames 和 IDispatch::Invoke 来绑定到自动化服务器的方法和属性。
创建使用晚期绑定的自动化客户端
启动 Microsoft Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。从 Visual C# 项目类型中选择 Windows 应用程序。默认情况下会创建 Form1。
在视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
双击 Button1。将出现该窗体的代码窗口。
在代码窗口中,将以下代码:
- 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
 - {
 - // Instantiate Excel.
 - objApp_Late = (object)new Excel.Application();
 - //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" );
 - }
 - }