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

时间:2014-05-26 15:54:15

标签: c#

我希望为使用早期绑定的以下代码行实现后期绑定。我怎样才能在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");

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

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

    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");