为什么可以创建一个COM接口的新实例? [英] Why is it possible to create a new instance of a COM interface?

查看:312
本文介绍了为什么可以创建一个COM接口的新实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有太多关于COM和coclasses的背景,所以我不太明白为什么我可以使用操作符与接口。从语言/框架无关的角度来看,它为什么会编译和运行正确:

I don't have very much background regarding COM nor coclasses, so I don't quite understand why I can use the new operator with an interface. From a language/framework-agnostic view, it's confusing why this compiles and runs correctly:

using Microsoft.Office.Interop.Excel;

public class ExcelProgram
{
    static void Main(string[] args)
    {
        Application excel = new Application();
    }
}

检查应用程序在Visual Studio 2010中显示我:

Inspecting Application in Visual Studio 2010 shows me:

using System.Runtime.InteropServices;

namespace Microsoft.Office.Interop.Excel
{
    // Summary:
    //     Represents the entire Microsoft Excel application.
    [Guid("000208D5-0000-0000-C000-000000000046")]
    [CoClass(typeof(ApplicationClass))]
    public interface Application : _Application, AppEvents_Event
    {
    }
}

幕后发生了什么?

推荐答案

这只适用于COM接口,我相信。 Marc Gravell在此处提供了解释。

This is only possible for COM interfaces, I believe. Marc Gravell has an explanation here.

简单的答案是COM接口可以与默认实现类配对,这样当你实例化接口时,你实际上创建了一个默认实现类的实例。在您的示例中的 Application 接口的情况下,显示为 ApplicationClass

The short answer is that a COM interface can be paired with a "default" implementation class, so that when you "instantiate" the interface you're actually creating an instance of that default implementation class. In the case of the Application interface in your example, that appears to be ApplicationClass.

这篇关于为什么可以创建一个COM接口的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆