gpt4 book ai didi

c# - _Application 和 Application 有什么区别

转载 作者:太空狗 更新时间:2023-10-29 19:51:26 25 4
gpt4 key购买 nike

为什么要使用 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 中有解释(强调已添加):

Application interface :

[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.

_Application interface :

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com