enum(C# 参考)enum (C# Reference)

enum 关键字用于声明枚举,一种包含一组被称为枚举数列表的已命名常数的不同类型。The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

通常最好是直接在命名空间内定义枚举,以便命名空间中的所有类都可以同样方便地访问它。Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. 但是,也可能会在类或结构中嵌套枚举。However, an enum can also be nested within a class or struct.

默认情况下,第一个枚举数具有值 0,并且每个连续枚举数的值将增加 1。By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. 例如,在以下枚举中, Sat 的值为 0Sun 的值为 1Mon 的值为 2,依次类推。For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.

enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

枚举数可以使用初始值设定项来替代默认值,如下面的示例中所示。Enumerators can use initializers to override the default values, as shown in the following example.

enum Day {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

在此枚举中,强制元素的序列从 1 开始,而不是 0In this enumeration, the sequence of elements is forced to start from 1 instead of 0. 但建议包括一个值为 0 的常量。However, including a constant that has the value of 0 is recommended. 有关详细信息,请参阅枚举类型For more information, see Enumeration Types.

每个枚举类型都有一个可以为任意整型数值类型的基础类型。Every enumeration type has an underlying type, which can be any integral numeric type. char 类型不能为枚举的基础类型。The char type cannot be an underlying type of an enum. 枚举元素的默认基础类型是 int。若要声明另一整型的枚举(如 byte),则请在后跟该类型的标识符后使用冒号,如以下示例所示。The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.

enum Day : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

枚举类型的变量可在基本类型范围内分配到任何值;这些值不限于已命名常数。A variable of an enumeration type can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

enum E 的默认值是由表达式 (E)0生成的值。The default value of an enum E is the value produced by the expression (E)0.

备注

枚举数名称中不能含有空格。An enumerator cannot contain white space in its name.

基础类型指定为每个枚举数分配多少存储空间。The underlying type specifies how much storage is allocated for each enumerator. 但要将 enum 类型转换为整型,则必须使用显示转换。However, an explicit cast is necessary to convert from enum type to an integral type. 例如,以下语句通过使用转换将 Sun 转换为 ,从而将枚举数 赋值为 enum int int类型的变量。For example, the following statement assigns the enumerator Sun to a variable of the type int by using a cast to convert from enum to int.

int x = (int)Day.Sun;

当你将 System.FlagsAttribute 应用到包含可与按位 OR 运算组合的元素的枚举中时,该特性与某些工具一起使用时会影响 enum 的行为。When you apply System.FlagsAttribute to an enumeration that contains elements that can be combined with a bitwise OR operation, the attribute affects the behavior of the enum when it is used with some tools. 当你使用工具(如 Console 类方法和表达式计算器)时,你可以注意到这些更改。You can notice these changes when you use tools such as the Console class methods and the Expression Evaluator. (请参阅第三个示例。)(See the third example.)

可靠编程Robust programming

正如任何常量一样,对枚举的各项值的所有引用在编译时都会转换为数字参数。Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time. 这可能会造成如常量中所述的潜在版本问题。This can create potential versioning issues as described in Constants.

将其他值分配到枚举的新版本,或者在新版本中更改枚举成员的值,会导致出现相关源代码问题。Assigning additional values to new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependent source code. 通常在 switch 语句中使用枚举值。Enum values often are used in switch statements. 如果已将其他元素添加到 enum 类型,则 switch 语句的默认部分可被意外地选中。If additional elements have been added to the enum type, the default section of the switch statement can be selected unexpectedly.

如果其他开发人员使用你的代码,则在将新元素添加到任何 enum 类型时应提供有关他们的代码应该如何响应的准则。If other developers use your code, you should provide guidelines about how their code should react if new elements are added to any enum types.

示例Example

在下面的示例中,已声明枚举 DayIn the following example, an enumeration, Day, is declared. 已将两个枚举数显式转换为整数,并赋值为整数变量。Two enumerators are explicitly converted to integer and assigned to integer variables.

public class EnumTest
{
    enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

    static void Main()
    {
        int x = (int)Day.Sun;
        int y = (int)Day.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}
/* Output:
   Sun = 0
   Fri = 5
*/

示例Example

以下示例中,使用基类型选项来声明其成员是 enum 类型的 longIn the following example, the base-type option is used to declare an enum whose members are of type long. 请注意,即使该枚举的基础类型是 long,仍然需通过使用转换将枚举成员显式转换为类型 longNotice that even though the underlying type of the enumeration is long, the enumeration members still must be explicitly converted to type long by using a cast.

public class EnumTest2
{
    enum Range : long { Max = 2147483648L, Min = 255L };
    static void Main()
    {
        long x = (long)Range.Max;
        long y = (long)Range.Min;
        Console.WriteLine("Max = {0}", x);
        Console.WriteLine("Min = {0}", y);
    }
}
/* Output:
   Max = 2147483648
   Min = 255
*/

示例Example

下面的代码示例说明了 System.FlagsAttribute 声明中 enum 特性的使用和作用。The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.

// Add the attribute Flags or FlagsAttribute.
[Flags]
public enum CarOptions
{
    // The flag for SunRoof is 0001.
    SunRoof = 0x01,
    // The flag for Spoiler is 0010.
    Spoiler = 0x02,
    // The flag for FogLights is 0100.
    FogLights = 0x04,
    // The flag for TintedWindows is 1000.
    TintedWindows = 0x08,
}

class FlagTest
{
    static void Main()
    {
        // The bitwise OR of 0001 and 0100 is 0101.
        CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;

        // Because the Flags attribute is specified, Console.WriteLine displays
        // the name of each enum element that corresponds to a flag that has
        // the value 1 in variable options.
        Console.WriteLine(options);
        // The integer value of 0101 is 5.
        Console.WriteLine((int)options);
    }
}
/* Output:
   SunRoof, FogLights
   5
*/

注释Comments

如果删除 Flags,则示例将显示以下值:If you remove Flags, the example displays the following values:

5

5

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also