在 .NET Framework 中,枚举集合中对象的接口必须继承 IEnumerable 接口。 IEnumerable 会公开一个方法 GetEnumerator。 非托管 COM 调度接口包含一个具有特殊 DISPID (-4) 的成员 (DISPID_NEWENUM),以表明该接口是可枚举的。 导入时,custom 特性会强制非托管 COM 接口实现 IEnumerable。 此 custom 特性的语法如下:
GUID = B64784EB-D8D4-4d9b-9ACD-0E30806426F7
Value = anything
![]() |
---|
您可以只将 IEnumerable 自定义类型库特性应用到仅支持调度的接口(调度接口)或双重接口。从 IUnknown 派生的接口不能继承 IEnumerable;因此,如果将 custom 特性应用到从 IUnknown 派生的接口,则类型库导入程序会忽略该特性。 |
示例
下面的示例是用接口定义语言 (IDL) 编写的,它演示如何使用 IEnumerable custom 类型库特性来强制 IMyClass 继承 IEnumerable:
[
object,
uuid(40E86021-CAD7-493B-BF09-43811D821BA7),
dual,
helpstring("IMyClass Interface"),
pointer_default(unique),
// Use the IEnumerable custom attribute.
custom(B64784EB-D8D4-4d9b-9ACD-0E30806426F7,"")
]
interface IMyClass : IDispatch
{
};
[
uuid(3ACBCEB2-9D52-46FA-97E0-063310CFD776),
helpstring("MyClass Class")
]
coclass MyClass
{
[default] interface IMyClass;
};
导入类型库后得到的 Microsoft 中间语言 (MSIL) 看上去类似下面这样:
.class interface public abstract auto ansi import IMyClass
implements [mscorlib]System.Collections.IEnumerable
{
...
} // This is the end of class MyClass.
一般而言,如果在检查 MSIL 之后代码不实现 IEnumerable,可以使用此 custom 特性来强制实现。