Ms word 为什么可以在Office Interop中创建接口实例?

Ms word 为什么可以在Office Interop中创建接口实例?,ms-word,Ms Word,在使用Office互操作类时,我已经多次看到这种情况 this.CustomXMLParts.Add(MyResources.Data, new Office.CustomXMLSchemaCollection()); 如果将鼠标悬停在CustomXMLSchemaCollection类上,它将显示为一个接口。那我怎么能在上面做一个新的呢?有什么好处? 顺便说一句,这段代码可以编译并运行。您不是在创建CustomXMLSchemaCollection接口的实例,而是在创建CustomXMLSc

在使用Office互操作类时,我已经多次看到这种情况

this.CustomXMLParts.Add(MyResources.Data, new Office.CustomXMLSchemaCollection());
如果将鼠标悬停在CustomXMLSchemaCollection类上,它将显示为一个接口。那我怎么能在上面做一个新的呢?有什么好处?
顺便说一句,这段代码可以编译并运行。

您不是在创建
CustomXMLSchemaCollection
接口的实例,而是在创建
CustomXMLSchemaCollectionClass
coclass的实例

CustomXMLSchemaCollection
接口的定义是:

[Guid("000CDB02-0000-0000-C000-000000000046")]
[CoClass(typeof(CustomXMLSchemaCollectionClass))]
public interface CustomXMLSchemaCollection : _CustomXMLSchemaCollection
{
}
这意味着实现接口的指定coclass是
CustomXMLSchemaCollectionClass
。我的猜测是,当C#编译器看到新的for
CustomXMLSchemaCollection
接口时,它会根据接口提供的属性将其转换为创建
CustomXMLSchemaCollectionClass
的COM实例

写了这个简单的例子之后:

namespace ConsoleApplication2
{
    using System;
    using Office = Microsoft.Office.Core;

    class Program
    {
        static void Main(string[] args)
        {
            Office.CustomXMLSchemaCollection test = new Office.CustomXMLSchemaCollection();
        }
    }
}
我刚刚运行并获得以下MSIL:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] class [Interop.Microsoft.Office.Core]Microsoft.Office.Core.CustomXMLSchemaCollection test)
  IL_0000:  nop
  IL_0001:  newobj     instance void [Interop.Microsoft.Office.Core]Microsoft.Office.Core.CustomXMLSchemaCollectionClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ret
} // end of method Program::Main

正如您所看到的,构建的类是
CustomXMLSchemaCollectionClass
,以证明我最初的假设。

OK COM Magic再次发挥作用。-CoClass属性似乎是这种偏离路径行为的关键。谢谢