Csharp 简明教程

C

枚举是一组命名的整型常量。枚举类型使用 enum 关键字声明。

An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.

C# 枚举是值数据类型。换句话说,枚举包含自己的值,不能继承或无法传递继承。

C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

Declaring enum Variable

声明枚举的一般语法为:

The general syntax for declaring an enumeration is −

enum <enum_name> {
   enumeration list
};

其中,

Where,

  1. The enum_name specifies the enumeration type name.

  2. The enumeration list is a comma-separated list of identifiers.

枚举列表中的每个符号都表示一个整数,比它前面的符号大 1。默认情况下,第一个枚举符号的值为 0。例如:

Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −

enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Example

以下示例演示了 enum 变量的使用:

The following example demonstrates use of enum variable −

using System;

namespace EnumApplication {
   class EnumProgram {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args) {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;

         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Monday: 1
Friday: 5