如何在c#forMicrosoft.office.interop.word中实现后期绑定?

我想为使用早期绑定的以下代码行实现后期绑定。 我怎样才能在C#中实现它?

当我删除Microsoft.office.interop.word引用时,我收到一些错误,这些错误在以下代码的注释中提到。 Folloowing是我用来将word文档转换为pdf的代码。

Type wordType = Type.GetTypeFromProgID("Word.Application"); dynamic Word = Activator.CreateInstance(wordType); object oMissing = System.Reflection.Missing.Value; DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder"); FileInfo wordFile = new FileInfo(fileName); Word.Visible = false; Word.ScreenUpdating = false; Object filename = (Object)wordFile.FullName; var doc = Word.Documents.Open(ref filename); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); /*Getting an error in WdSaveFormat */ object fileFormat = WdSaveFormat.wdFormatPDF; doc.SaveAs(ref outputFileName, ref fileFormat); /*Getting an error in WdSaveOptions */ object saveChanges = WdSaveOptions.wdDoNotSaveChanges; /*Getting an error in _Document*/ ((_Document)doc).Close(ref saveChanges); doc = null; Word.Quit(); MessageBox.Show("Successfully converted"); 

从历史上看,后期绑定是可能的(并且仍然是!)与reflection:

 object word = ...; object[] args = new object [] { oMissing, oMissing, oMissing }; word.GetType().InvokeMember( "Quit", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, word, args ); 

随着C#4中动态的引入,后期绑定只需要切换到动态绑定器:

 dynamic word = ...; word.Quit(); 

它真的很简单,你甚至不必将这些可选参数传递给Quit方法。 唯一的缺点是动态类型代码没有智能感知。

更多关于迪诺的文章:

http://msdn.microsoft.com/en-us/magazine/ff714583.aspx

做了以下改动,现在工作正常。

  Type wordType = Type.GetTypeFromProgID("Word.Application"); dynamic Word = Activator.CreateInstance(wordType); object oMissing = System.Reflection.Missing.Value; DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder"); FileInfo wordFile = new FileInfo(fileName); Word.Visible = false; Word.ScreenUpdating = false; Object filename = (Object)wordFile.FullName; var doc = Word.Documents.Open(ref filename); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); /*in the WdSaveFormat enum, 17 is the value for pdf format*/ object fileFormat = 17; doc.SaveAs(ref outputFileName, ref fileFormat); /in the WdSaveOptions enum, 0 is for Do not save pending changes.*/ object saveChanges = 0; doc.Close(ref saveChanges); doc = null; Word.Quit(); MessageBox.Show("Successfully converted");