我在c#类库中有以下代码...
public static class foo
{
public enum bar
{
bsNone = -1,
bsSolid = 0,
bsDash = 1
}
}
在VB.Net Winforms应用程序中,我将enum引用为属性的返回类型:
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
当我构建VB.Net项目时,我收到以下警告:
Return type of function 'LeftBorderStyle' is not CLS-compliant.
你能告诉我为什么enum不符合CLS吗?
答案 0 :(得分:3)
这种情况正在发生,因为您是从标记为CLS-Compliant的程序集中公开公开的类型,该程序集来自不符合CLS的程序集。
请注意,您可以使用在CLS兼容程序集中不符合CLS的类型;但是你不允许暴露这种类型。
例如,假设您在非CLS兼容程序集中具有此类:
namespace NonCLSCompliantAssembly
{
public class Class1
{
public enum MyEnum
{
Red,
Green,
Blue
}
}
}
现在假设在符合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;
}
}
}
编译器将 NOT 警告您MyTest1()'s
使用来自非兼容程序集的类型MyEnum
,因为它仅在内部使用。
但它将警告您将其公开为MyTest2()
的公共返回类型。
如果通过将[assembly: CLSCompliant(true)]
添加到AssemblyInfo.cs
来使符合非CLS的程序集符合要求,那么代码将全部编译而不会发出警告。
重申一下:如果您使用在不合规程序集中定义的类型,那么该类型将自动不合规,即使它只是像枚举这样的基本类型。
来自Microsoft documentation for CLSCompliantAttribute:
如果没有CLSCompliantAttribute应用于程序元素,则默认情况下:
程序集不符合CLS。
只有当封闭类型或程序集符合CLS时,该类型才符合CLS。
仅当类型符合CLS时,类型的成员才符合CLS。