Why would we want to apply the ClassInterface attribute to a class?

Ada*_*Lee 5 .net c#

[ClassInterface(ClassInterfaceType.None)]
Class Program()
{
}
Run Code Online (Sandbox Code Playgroud)

When would we need to apply the ClassInterface attribute to a class, as is done here?

dyl*_*web 5

ClassInterfaceAttribute用于声明您的类对 COM 调用者的可见程度,即您的类是否能够与尝试使用您的类的 COM 世界中的某些内容很好地配合。枚举中包含三个选项ClassInterfaceType,您可以将其指定为ClassInterfaceAttribute. 这里来自 MSDN,下面是三个类声明的示例,每个类声明都有不同的 InterfaceType 选择:

ClassInterfaceAttribute在 MSDN 上

ClassInterfaceType在 MSDN 上

下面说明了 的使用ClassInterfaceAttribute

// This one will not be visible to COM clients.
[ClassInterface(ClassInterfaceType.None)]
public class MyClass1
{

}

// This one will provide an interface for COM clients, 
// but only when/if one is requested of it.
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class MyClass2
{

}

// This one will, immediately upon instantiation, 
// automatically include an interface for COM clients.
[ClassInterface(ClassInterfaceType.AutoDual)]
public class MyClass3
{

}
Run Code Online (Sandbox Code Playgroud)