与枚举和公共类混淆 - 为什么它不起作用?

发布于 2024-10-03 19:41:19 字数 265 浏览 4 评论 0原文


具有以下代码,它不断报告可访问性不一致,但我不明白为什么。这取决于程序类是否公开:

enum Test
    {A,B}

    public class Program  //when I remove public, it works
    {
        public Test a = Test.A;

        static void Main(string[] args)
        {

        }
    }

Having the following code, it keeps reporting inconsisteng accessibility but I do not understand why. It depends on the Program class being or not being public:

enum Test
    {A,B}

    public class Program  //when I remove public, it works
    {
        public Test a = Test.A;

        static void Main(string[] args)
        {

        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蓝梦月影 2024-10-10 19:41:19

您尚未在枚举声明中添加访问修饰符,然后将其公开为 Program 类的 public 字段。如果您不声明访问修饰符,则它是私有

public enum Test { A, B }

You haven't put an access modifier on your enum declaration, and then you are exposing it as a public field of your Program class. If you don't declare an access modifier, it is private.

public enum Test { A, B }
却一份温柔 2024-10-10 19:41:19

由于您尚未在枚举上显式声明访问修饰符(即 publicprotectedinternal),因此它采用默认值(即是类和枚举的内部)。然后,您通过 Program 类的 public 字段公开该枚举,这是不允许的,因为枚举在其程序集外部不可见。

您需要将枚举声明为 public,或者将字段的访问修饰符更改为 internalprivate

当您从 Program 类中删除 public 时,它会起作用,因为它将 Program 类更改为内部类 - 与枚举相同。这很好,因为他们都没有公开曝光。

Because you have not explicitly declared an access modifier (ie. public, protected, internal) on your enum, it takes the default value (which is internal for classes and enums). You are then exposing that enum via a public field of your Program class, which is not allowed as the enum is not visible outside of its assembly.

You need to either declare the enum as public, or change the access modifier of the field to internal or private.

It works when you remove public from the Program class because it changes the Program class to be internal - the same as the enum. This is fine as neither of them are publicly exposed.

白况 2024-10-10 19:41:19

您不能将属性公开,因为枚举是私有的。如果有人使用您的程序并且编译器会告诉您,则公共属性将是外部公共的。

You can't make the property public because the enum is private. The public property would be externally public should someone use your program and the compiler tells you about it.

著墨染雨君画夕 2024-10-10 19:41:19

您可能需要将枚举设置为公共

you probably need to set the enumeration to public

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文