在类体之外的命名空间内的枚举的定义 [英] Definition of enums outside the class body but inside namespace

查看:413
本文介绍了在类体之外的命名空间内的枚举的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我遇到了一些这样的代码。

Today, I ran into some code that goes like this.

namespace Foo
{

    public enum Game{ High, Low};
    public enum Switch{On, Off};

    public class Bar()
    {
    // Blah
    }
}

我无法弄清楚它之间的区别和声明该类内的枚举是什么。 AFAIK,你仍然可以覆盖类中的这些枚举。

I could not figure out what the difference between that and declaring the enums inside the class was. AFAIK, you can still "override" those enums inside the class.

推荐答案

枚举是类型,就像类一样。当你在一个类中声明一个枚举时,它只是一个嵌套类型。嵌套枚举只是使用与外部范围中声明的名称相同的其他枚举名称,但您仍然可以通过其完全限定名称(在示例中使用命名空间前缀)引用隐藏的枚举。

Enums are types, just like classes. When you declare an enum inside a class, it's just a nested type. A nested enum just hides other enums with the same name that are declared in outer scopes, but you can still refer to the hidden enum through its fully qualified name (using the namespace prefix, in your example).

是否声明顶级枚举或嵌套枚举的决定取决于您的设计,以及这些枚举是否将被类以外的其他任何内容使用。您也可以将嵌套的枚举私有或保护其封闭类型。但是,顶级枚举更常见。

The decision whether to declare a top level enum or a nested enum depends on your design and whether those enums will be used by anything other than the class. You can also make a nested enum private or protected to its enclosing type. But, top level enums are far more common.

这篇关于在类体之外的命名空间内的枚举的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆