【问题标题】:Use of enum is not CLS-compliant枚举的使用不符合 CLS
【发布时间】:2015-10-13 11:02:29
【问题描述】:

我在 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?否则,您将收到该警告。
  • 没有。但我不明白为什么课堂上的其他 4,000 行代码没有给我 CLS 合规性警告?只有枚举?
  • @Backs - 谢谢,那篇文章没有解释为什么枚举不符合 CLS。
  • 能否请您告诉我您用于为属性分配值/访问值的代码

标签: c# vb.net enums cls-compliant


【解决方案1】:

发生这种情况是因为您从标记为符合 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()'s 使用来自非兼容程序集的类型 MyEnum,因为它只在内部使用。

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

如果您通过将[assembly: CLSCompliant(true)] 添加到AssemblyInfo.cs 来使非 CLS 兼容程序集兼容,则代码将全部编译而不会发出警告。

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

来自Microsoft documentation for CLSCompliantAttribute

如果没有 CLSCompliantAttribute 应用于程序元素,则默认情况下:

  • 程序集不符合 CLS。

  • 仅当其封闭类型或程序集符合 CLS 时,该类型才符合 CLS。

  • 仅当类型符合 CLS 时,类型的成员才符合 CLS。

【讨论】:

  • 为什么枚举不合规?
  • @Rob 这是不合规的,因为它是在不合规的程序集中定义的。我在回复的第一句话中就说过... ;)
  • 谢谢@Matthew,问题是为什么编译器只抱怨不合规程序集中的枚举而不是其中的数千个其他类?这是编译器只是抓住了它可以抱怨的最近的东西吗?
  • @RichardMoore 就像我在回答中所说的那样,您可以使用其他类,只是不允许从公共方法返回它们或将它们作为参数传递给公共方法你的大会。看看我的例子,上面写着“这不会发出警告”。
猜你喜欢
  • 1970-01-01
  • 2016-02-06
  • 1970-01-01
  • 2012-12-12
  • 2023-04-01
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
相关资源
最近更新 更多