与枚举和公共类混淆 - 为什么它不起作用?
具有以下代码,它不断报告可访问性不一致,但我不明白为什么。这取决于程序类是否公开:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您尚未在枚举声明中添加访问修饰符,然后将其公开为
Program
类的public
字段。如果您不声明访问修饰符,则它是私有
。You haven't put an access modifier on your enum declaration, and then you are exposing it as a
public
field of yourProgram
class. If you don't declare an access modifier, it isprivate
.由于您尚未在枚举上显式声明访问修饰符(即
public
、protected
、internal
),因此它采用默认值(即是类和枚举的内部
)。然后,您通过Program
类的public
字段公开该枚举,这是不允许的,因为枚举在其程序集外部不可见。您需要将枚举声明为
public
,或者将字段的访问修饰符更改为internal
或private
。当您从
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 isinternal
for classes and enums). You are then exposing that enum via apublic
field of yourProgram
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 tointernal
orprivate
.It works when you remove
public
from theProgram
class because it changes theProgram
class to be internal - the same as the enum. This is fine as neither of them are publicly exposed.您不能将属性公开,因为枚举是私有的。如果有人使用您的程序并且编译器会告诉您,则公共属性将是外部公共的。
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.
您可能需要将枚举设置为公共
you probably need to set the enumeration to public