本文介绍了请说明为什么我可以实例化“申请” Excel VSTO中的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有以下C#代码,工作正常。它启动了一个新的Excel实例。

I have the following C# code in my application which works just fine. It launches a new instance of Excel.

private readonly Microsoft.Office.Interop.Excel.Application _application;
_application = new Microsoft.Office.Interop.Excel.Application();
_application.Visible = true;

我最近才注意到是一种接口类型。

I only recently noticed that Application is an interface type. What exactly is going on and how is it possible?

推荐答案

编译器允许您实例化界面,如果它们使用属性标识实现它们的具体类(以及和)。当您实例化界面时,您实际上将在幕后实例化这个具体的类。

The compiler allows you to instantiate interfaces if they’re decorated with a CoClass attribute identifying the concrete class that implements them (as well as a ComImport and a Guid). When you instantiate the interface, you would actually be instantiating this concrete class behind-the-scenes.

此功能旨在用作COM导入类型的管道。请注意Outlook如何接口由一个名为:

This "feature" is intended to be used as plumbing for COM imported types. Notice how the Outlook Application interface is backed by a concrete class named ApplicationClass:

[GuidAttribute("00063001-0000-0000-C000-000000000046")]
[CoClassAttribute(typeof(ApplicationClass))]
public interface Application : _Application, ApplicationEvents_11_Event

在大多数情况下,您应该将不应用于您自己的界面。但是,为了演示,我们可以显示编译器可以利用这种在代码中实例化接口的可能性。考虑以下简单示例(GUID是随机的):

In most circumstances, you should not go applying these attributes to your own interfaces. However, for the sake of demonstration, we can show that the compiler will allow you to take advantage of this possibility for instantiating interfaces in your code. Consider the following simple example (the GUID is random):

[ComImport]
[Guid("175EB158-B655-11E1-B477-02566188709B")]
[CoClass(typeof(Foo))]
interface IFoo
{
    string Bar();
}

class Foo : IFoo
{
    public string Bar()
    {
        return "Hello world";
    }
}

使用上述声明,您可以创建一个您自己的 IFoo 接口:

Using the above declarations, you can create an instance of your own IFoo interface:

IFoo a = new IFoo();
Console.WriteLine(a.Bar());
// Output: "Hello world"

修改:虽然正确地注意到,Excel 实例没有使用MSDN上的 CoClass 进行装饰,这似乎是MSDN的遗漏。来自 Microsoft.Office.Interop.Excel 程序集的反编译签名是:

Edit: Although jonnyGold correctly notes that the Excel Application instance is not decorated with CoClass on MSDN, this appears to be an MSDN omission. The decompiled signature from the Microsoft.Office.Interop.Excel assembly is:

[CoClass(typeof(ApplicationClass)), Guid("000208D5-0000-0000-C000-000000000046")]
[ComImport]
public interface Application : _Application, AppEvents_Event

这篇关于请说明为什么我可以实例化“申请” Excel VSTO中的界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 07:02