Ambiguity in Word Interop code [duplicate]

≯℡__Kan透↙ 提交于 2019-12-01 03:26:37

To resolve the ambiguity, use:

((Microsoft.Office.Interop.Word._Document)docs).Close(ref nullobject, ref nullobject, ref nullobject);    
((Microsoft.Office.Interop.Word._Application)wordObject).Quit(ref nullobject, ref nullobject, ref nullobject);

Try casting your docs first:

((_Document)docs).Close(ref nullobject, ref nullobject, ref nullobject);

The Microsoft.Office.Interop.Word.Document interface implements both the DocumentEvents2_Event and _Document interfaces. Each have a close method, and the compiler is having trouble determining which you mean.

Alternatively, you could declare your docs variable as a _Document in the first place:

Microsoft.Office.Interop.Word._Document docs = wordObject.Documents.Open ...

The same resolution can be used for ambiguities on your wordObject, casting it to an _Application.

The proposed solutions works fine, but it leaves ReSharper with an Ambiguous Invocation error that you can't get rid of except for using the old "Ignore Errors" trick in the R# Errors dialog, even though the compiler is happy enough with it.

I couldn't really get a good solution from R# and it only comes up in a few places so the least-bad answer I found that works and doesn't produce either Visual Studio or R# errors is to cast to a dynamic.

((dynamic) Doc).Close();

Not ideal, but I just hold my nose and use it. If you are going to use it more than once you can obviously save to a dynamic variable. You could technically use the dynamic for everything (it's just late-bound COM), but you'd lose all intelliSense so I only use it on the few methods and events where it comes up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!