为什么可以在 Office Interop 中创建接口实例?
我在使用 Office Interop 类时多次看到这种情况。
this.CustomXMLParts.Add(MyResources.Data, new Office.CustomXMLSchemaCollection());
如果我将鼠标悬停在 CustomXMLSchemaCollection 类上,它会显示为一个界面。 那我怎么可以做一个新的呢? 是什么赋予了? 顺便说一句,这段代码可以编译并运行。
I've seen this quite a few times while using Office Interop classes
this.CustomXMLParts.Add(MyResources.Data, new Office.CustomXMLSchemaCollection());
If I hover over the CustomXMLSchemaCollection class, it shows up as an interface. Then how come I can do a new on it ? What gives?
BTW this code compiles and works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不是在创建
CustomXMLSchemaCollection
接口的实例,而是创建CustomXMLSchemaCollectionClass
coclass 的实例。CustomXMLSchemaCollection
接口的定义是:这意味着实现该接口的指定组件类是
CustomXMLSchemaCollectionClass
。 我的猜测是,当 C# 编译器看到新的CustomXMLSchemaCollection
接口时,它会根据该接口提供的属性将其转换为创建CustomXMLSchemaCollectionClass
的 COM 实例。写完这个简单的例子后:
我刚刚运行了 ildasm 并获得以下 MSIL:
如您所见,构造的类是
CustomXMLSchemaCollectionClass
以证明我最初的假设。You are not creating an instance of the
CustomXMLSchemaCollection
interface but an instance of theCustomXMLSchemaCollectionClass
coclass.The definition for
CustomXMLSchemaCollection
interface is:This means that the designated coclass that implements the interface is
CustomXMLSchemaCollectionClass
. My guess is that when the C# compiler sees the new forCustomXMLSchemaCollection
interface it translates it to create a COM instance of theCustomXMLSchemaCollectionClass
based on the attributes provided with the interface.After writing this simple example:
I just ran ildasm and get the following MSIL:
As you can see the class that is constructed is
CustomXMLSchemaCollectionClass
to prove my initial assumption.