简体   繁体   English

C#中枚举的默认访问修饰符

[英]default access modifier for enum in C#

According to MSDN here and here (as well as the accepted answer to this qstn ), the default accessibility for enums is public . 根据MSDN 此处此处 (以及此qstn接受答案 ),枚举的默认可访问性是public However, this code: 但是,这段代码:

public class Test
{
    enum Color { RED, BLUE, GREEN };
    public void SetColor(Color c) { }
}

will raise this compile error: 会引发这个编译错误:

Error 1 Inconsistent accessibility: parameter type 'Test.Color' is less accessible than method 'Test.SetColor(Test.Color)'

(which is the same error you get when you set the enum as private .) This error can only be resolved by explicitly modifying enum as public . (将枚举设置为private时会出现同样的错误。)只能通过将枚举显式修改为public来解决此错误。 Is the documentation incorrect? 文档不正确吗?

[I'm compiling with C# 2010 and .NET 4.0.] [我正在使用C#2010和.NET 4.0进行编译。]

That is not true. 事实并非如此。

The default accessibility for enum types is the same as any other type; 枚举类型的默认可访问性与任何其他类型相同; internal for top-level types and private for nested types. 顶级类型的内部和嵌套类型的私有。

The pages you linked to state that the default (and, in fact, only) accessibility level for enum members ( Red , Blue , etc) is public. 您链接的页面表明枚举成员RedBlue等)的默认(实际上是唯一)可访问性级别是公共的。

The mentioned MSDN articles and SO answer refer to "enum member" - ieeg Test.Color.RED , not Test.Color as the enum itself. 上面提到的MSDN文章和SO答案都是指“枚举成员” - ieeg Test.Color.RED ,而不是Test.Color作为枚举本身。

Test.Color is a member of class - thus private. Test.Color是类的成员 - 因此是私有的。

That table is referring to the members ; 该表是指成员 ; the members are "RED", "BLUE" and "GREEEN", and are indeed public literal constants, and accessibility specifies are not permitted. 成员是“RED”,“BLUE”和“GREEEN”,并且确实是公共文字常量,并且不允许使用可访问性。

Contrast, say, to the members of a class (fields, methods, constants, etc); 比如说,对比一个类的成员 (字段,方法,常量等); here, as per the table, the default is "private", although you can specify higher accessibility. 这里,根据表格,默认为“私有”,但您可以指定更高的可访问性。

I believe that because you're declaring inside the class without a modifier, it assumes to be private as it's the standard behavior in a class. 我相信,因为你在没有修饰符的情况下在类中声明,它假定是私有的,因为它是类中的标准行为。 Specify public that should solve the issue. 指定应该解决问题的公共。 However, note that Code Analysis will recommend this enum be placed outside the class. 但请注意,Code Analysis会建议将此枚举放在课堂外。

it is because you dont have public, protected, internal on your enum, it takes the default value (which is internal for classes and enums) 这是因为你的枚举上没有public,protected,internal,它取默认值(这是类和枚举的内部)

sorry for the confusion, 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 如果有人使用您的程序并且编译器告诉您有关它,公共财产将在外部公开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM