为什么要使用 Word 定义这样的变量:
Dim Word As Microsoft.Office.Interop.Word._Application
或
Microsoft.Office.Interop.Word._Application Word;
然后这样设置:
Word = New Microsoft.Office.Interop.Word.Application
或
Word = new Microsoft.Office.Interop.Word.Application();
Application 和 _Application 有什么区别?
我怀疑一个可能是类而另一个是接口(interface),或者一个可能是公共(public)的而另一个是私有(private)的,但这对我来说仍然没有意义。
我希望有人能给我解释一下。越详细越好。
最佳答案
两者都是接口(interface),Application
接口(interface)继承自_Application
接口(interface)(连同ApplicationEvents4_Event
接口(interface))。
那么什么时候用什么?差异在 MSDN 中有解释(强调已添加):
[GuidAttribute("00020970-0000-0000-C000-000000000046")]
public interface Application : _Application,
ApplicationEvents4_Event
This is a .NET interface derived from a COM coclass that is required by managed code for interoperability with the corresponding COM object. Use this derived interface to access all method, property, and event members of the COM object. However, if a method or event you want to use shares the same name under the same COM object, cast to the corresponding primary interface to call the method, and cast to the latest events interface to connect to the event. Refer to this topic for information about the COM object.
[TypeLibType(4304)]
[Guid("00020970-0000-0000-C000-000000000046")]
[ComImport]
public interface _Application { ... }
This is a primary interface in a COM coclass that is required by managed code for interoperability with the corresponding COM object. Use this primary interface only when the method you want to use shares the same name as an event of the COM object; in this case, cast to this interface to call the method, and cast to the latest events interface to connect to the event. Otherwise, use the .NET interface that is derived from the COM coclass to access methods, properties, and events of the COM object.
实际后果
简而言之:在您的代码中使用 Application
而不是 _Application
,除非您必须这样做,因为方法名称和事件名称之间存在歧义。
例如 Application.Quit
之间存在这种歧义。事件(应用程序退出时触发)和 Application.Quit(ref Object SaveChanges, ref Object OriginalFormat, ref Object RouteDocument)
方法(调用时退出应用程序)。
为了调用该方法,您可以简单地编写(例如退出而不提示保存更改):
Application.Quit(false);
但是,这可能会给您以下编译器警告:
Warning 3 Ambiguity between method 'Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group.
为避免警告,您可以将应用程序对象强制转换为 _Application
接口(interface):
((_Application)Application).Quit(false);
如果你想订阅事件,你需要将应用程序对象转换为合适的事件接口(interface):
((ApplicationEvents4_Event)Application).Quit += OnApplicationQuit;
private void OnApplicationQuit()
{
// handle event here
}
关于c# - _Application 和 Application 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40766117/