Why is it possible to create a new instance of a COM interface?

☆樱花仙子☆ 提交于 2019-12-19 16:13:07

问题


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();
    }
}

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
    {
    }
}

What is going on behind the scenes?


回答1:


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

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.



来源:https://stackoverflow.com/questions/4951835/why-is-it-possible-to-create-a-new-instance-of-a-com-interface

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