【问题标题】:Since when C# enums can be private?从什么时候开始 C# 枚举可以是私有的?
【发布时间】:2019-10-10 07:25:01
【问题描述】:

我认为这是不可能的,但不知何故你可以添加修饰符到 enumpublic 不同。

这段代码工作得很好,可以作为真正的私有成员(在包含类C之外无法访问:

namespace N {
    public class C {
        private enum E { ... }
    }
}

根据@Ben 的回答in this question 这应该是不可能的:

简短回答: 最小可能访问权限(参见 Jon Skeet 的回答)。

长答案:

非嵌套类型、枚举和委托可访问性可能只有内部或公共可访问性

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | none (always implicitly public)

interface            | internal  | public, internal

class                | internal  | public, internal

struct               | internal  | public, internal

delegate             | internal  | public, internal

嵌套类型和成员可访问性

                     | Default   | Permitted declared accessibilities
------------------------------------------------------------------
namespace            | public    | none (always implicitly public)

enum                 | public    | none (always implicitly public)

interface            | public    | none

class                | private   | All¹

struct               | private   | public, internal, private²

delegate             | private   | All¹

constructor          | private   | All¹

interface member     | public    | none (always implicitly public)

method               | private   | All¹

field                | private   | All¹

user-defined operator| none      | public (must be declared public)

¹ 全部 === 公开的、受保护的、内部的、私有的、受保护的内部

² 结构不能从结构或类继承(尽管它们可以,接口),因此 protected 不是有效的修饰符

嵌套类型的可访问性取决于它的可访问性 域,这由声明的可访问性决定 成员和直接包含的可访问域 类型。但是,嵌套类型的可访问域不能超过 包含类型的。

注意:CIL 还规定了受保护和内部(如 反对现有的受保护的“或”内部),但据我所知 这目前不能在 C# 中使用。


见:

http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
http://msdn.microsoft.com/en-us/library/ms173121.aspx
http://msdn.microsoft.com/en-us/library/cx03xt0t.aspx(我爱的人 Microsoft URI...)

【问题讨论】:

  • 枚举成员不能应用访问修饰符。从您的链接:“枚举成员始终是公开的,并且不能应用访问修饰符。”枚举本身可以设为私有。
  • 你可以把嵌套的枚举类型看成是它的父类的成员,所有的访问修饰符都允许在一个类的成员上。
  • 您好,我回滚了您的修订,因为它删除了问题的上下文。

标签: c# enums access-modifiers


【解决方案1】:

这是描述enum成员 的可访问性,而不是enum 本身。枚举的所有 成员 不能被赋予可访问性修饰符,并且始终是公共的。

所以你不能这样做:

public enum Foo
{
    public SomeValue = 1,
    internal AnotherValue = 2,
}

SomeValueAnotherValue 将始终隐式公开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2016-04-21
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多