在C#中创建接口实例 [英] Creating instance of interface in C#

查看:104
本文介绍了在C#中创建接口实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#中的MS Excel互操作,但我不理解这行特定代码的工作方式:

I'm working with MS Excel interop in C# and I don't understand how this particular line of code works:

var excel = new Microsoft.Office.Interop.Excel.Application();

其中Microsoft.Office.Interop.Excel.Application是一个接口,定义为:

where Microsoft.Office.Interop.Excel.Application is an INTERFACE defined as:

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

我在想,用CoClass属性修饰界面时会发生一些魔术,但是我们仍然有可能使用new关键字创建界面的实例吗?它不应该产生编译时错误吗?

I'm thinking that some magic happens when the interface is decorated with a CoClass attribute, but still how is it possible that we can create an instance of an interface with a new keyword? Shouldn't it generate a compile time error?

推荐答案

您实际上提到的代码创建了ApplicationClass类的实例,而CoClass属性正是该代码的作用.

Actually code that you mentioned created instance of the ApplicationClass class and that is what CoClass attribute does.

有关详细信息,请参见以下答案: C#编译器检测COM类型吗?

See this answer for details: How does the C# compiler detect COM types?

这篇关于在C#中创建接口实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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