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

5

我希望将以下使用早期绑定的代码实现为晚期绑定。我该如何在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(@"\\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");

你能给我们提供你的真实代码,并说明你想在哪个部分实现吗?编号列表并没有太大帮助。 - Farhad Alizadeh Noori
只需删除强制转换。 "Word" 和 "doc" 变量必须当然是 dynamic 类型。你将不得不使用整数代替枚举,这相当痛苦。没有太多的意义去这样惩罚自己。 - Hans Passant
2个回答

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


感谢Wiktor的回复。你的答复和链接帮助我更好地理解了组件对象。我已经修改了我的问题,请看一下。 - turbo88

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

1
不仅它能正常工作,而且代码也更加清晰易懂。 - Wiktor Zychla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接