gpt4 book ai didi

c# - 使用枚举不符合 CLS

转载 作者:太空狗 更新时间:2023-10-30 01:33:39 25 4
gpt4 key购买 nike

我在 C# 类库中有以下代码...

public static class foo
{
public enum bar
{
bsNone = -1,
bsSolid = 0,
bsDash = 1
}
}

在 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

当我构建 VB.Net 项目时,我收到以下警告:

Return type of function 'LeftBorderStyle' is not CLS-compliant.

你能告诉我为什么枚举不符合 CLS 吗?

最佳答案

发生这种情况是因为您从标记为符合 CLS 的程序集中公开了一种类型,而该类型来自不符合 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;
}
}
}

编译器不会警告您 MyTest1() 从非兼容程序集中使用类型 MyEnum,因为它仅在内部使用。

但它警告您将其公开为 MyTest2() 的公共(public)返回类型。

如果您通过将 [assembly: CLSCompliant(true)] 添加到 AssemblyInfo.cs 来使不符合 CLS 的程序集兼容,那么代码将全部编译而无需一个警告。

重申一下:如果您使用在不兼容的程序集中定义的类型,则该类型自动不兼容,即使它只是像枚举这样的基本类型。

来自Microsoft documentation for CLSCompliantAttribute :

If no CLSCompliantAttribute is applied to a program element, then by default:

  • The assembly is not CLS-compliant.

  • The type is CLS-compliant only if its enclosing type or assembly is CLS-compliant.

  • The member of a type is CLS-compliant only if the type is CLS-compliant.

关于c# - 使用枚举不符合 CLS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com