Ric*_*ore 6 c# vb.net enums cls-compliant
我在 ac# 类库中有以下代码...
public static class foo
{
public enum bar
{
bsNone = -1,
bsSolid = 0,
bsDash = 1
}
}
Run Code Online (Sandbox Code Playgroud)
在 VB.Net Winforms 应用程序中,我引用枚举作为属性的返回类型:
Private _LeftBorderStyle As foo.bar
Public Property LeftBorderStyle() As foo.bar
Get
Return _LeftBorderStyle
End Get
Set(ByVal value As foo.bar)
_LeftBorderStyle = value
End Set
End Property
Run Code Online (Sandbox Code Playgroud)
当我构建 VB.Net 项目时,我收到以下警告:
Return type of function 'LeftBorderStyle' is not CLS-compliant.
Run Code Online (Sandbox Code Playgroud)
你能告诉我为什么枚举不符合 CLS 吗?
发生这种情况是因为您从标记为 CLS-Compliant 的程序集中公开暴露了来自不符合 CLS 的程序集的类型。
请注意,您被允许消耗是不符合CLS在符合CLS的组件类型; 但是不允许公开这样的类型。
例如,假设您在不符合 CLS 的程序集中有此类:
namespace NonCLSCompliantAssembly
{
public class Class1
{
public enum MyEnum
{
Red,
Green,
Blue
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在假设您在引用非 CLS 兼容程序集的 CLS 兼容程序集中有以下类:
namespace CLSCompliantAssembly
{
public class Class1
{
// This does NOT give a warning.
public int MyTest1()
{
return (int) NonCLSCompliantAssembly.Class1.MyEnum.Red;
}
// This DOES give a warning.
public NonCLSCompliantAssembly.Class1.MyEnum MyTest2()
{
return NonCLSCompliantAssembly.Class1.MyEnum.Red;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译器不会警告您MyTest1()'s使用MyEnum 来自非兼容程序集的类型,因为它仅在内部使用。
但WILL警告你露出它的公共返回类型MyTest2()。
如果通过添加[assembly: CLSCompliant(true)]到使非 CLS 兼容程序集兼容AssemblyInfo.cs,则代码将全部编译而不会发出警告。
重申:如果您使用在不合规程序集中定义的类型,该类型自动不合规,即使它只是像枚举这样的基本类型。
来自CLSCompliantAttribute的Microsoft 文档:
如果没有 CLSCompliantAttribute 应用于程序元素,则默认情况下:
该程序集不符合 CLS。
仅当其封闭类型或程序集符合 CLS 时,类型才符合 CLS。
仅当类型符合 CLS 时,类型的成员才符合 CLS。