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



我想为下面使用早期绑定的代码行实现晚期绑定。我如何在c#中实现它?

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

    Type wordType = Type.GetTypeFromProgID("Word.Application");
        dynamic Word = Activator.CreateInstance(wordType);

        object oMissing = System.Reflection.Missing.Value;

        DirectoryInfo dirInfo = new DirectoryInfo(@"\serverfolder");
        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");

历史上,延迟绑定是可能的(现在仍然是!)与反射:

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方法。唯一的缺点是对动态类型的代码没有智能感知。

更多信息请参阅Dino的文章:

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(@"\serverfolder");
    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");

最新更新