列舉類型 (C# 程式設計手冊)Enumeration types (C# Programming Guide)

列舉類型 (也稱為列舉 (enumeration) 或列舉 (enum)) 提供有效率的方式,來定義一組可指派給變數的具名整數常數。An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. 例如,假設您必須定義一個變數,其值代表星期幾。For example, assume that you have to define a variable whose value will represent a day of the week. 該變數只會儲存七個有意義的值。There are only seven meaningful values which that variable will ever store. 若要定義這些值,您可以使用以 enum 關鍵字宣告的列舉類型。To define those values, you can use an enumeration type, which is declared by using the enum keyword.

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Month : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 

根據預設,每個項目在列舉中的基礎類型是 int。您可以使用冒號指定其他的整數數值類型,如上例所示。By default the underlying type of each element in the enum is int. You can specify another integral numeric type by using a colon, as shown in the previous example. 如需可能類型的完整清單,請參閱 enum (C# 參考)For a full list of possible types, see enum (C# Reference).

您可以透過轉換為基礎類型來驗證基礎數字值,如下例所示。You can verify the underlying numeric values by casting to the underlying type, as the following example shows.

Day today = Day.Monday;
int dayNumber =(int)today;
Console.WriteLine("{0} is day number #{1}.", today, dayNumber);

Month thisMonth = Month.Dec;
byte monthNumber = (byte)thisMonth;
Console.WriteLine("{0} is month number #{1}.", thisMonth, monthNumber);

// Output:
// Monday is day number #1.
// Dec is month number #11.

使用列舉而不使用數值類型的優點如下︰The following are advantages of using an enum instead of a numeric type:

  • 清楚指定用戶端程式碼的哪些值對變數有效。You clearly specify for client code which values are valid for the variable.

  • 在 Visual Studio 中,IntelliSense 會列出已定義的值。In Visual Studio, IntelliSense lists the defined values.

當您不為列舉程式清單中的項目指定值時,值會自動遞增 1。When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1. 在上例中,Day.Sunday 的值為 0,Day.Monday 的值為 1,依此類推。In the previous example, Day.Sunday has a value of 0, Day.Monday has a value of 1, and so on. 當您建立新的 Day 物件時,如未明確指定其值,則它會有預設值 Day.Sunday (0)。When you create a new Day object, it will have a default value of Day.Sunday (0) if you do not explicitly assign it a value. 當您建立列舉時,請選取最符合邏輯的預設值,並指定其值為零。When you create an enum, select the most logical default value and give it a value of zero. 這會造成所有的列舉都是預設值,如果它們在建立時未明確指派值。That will cause all enums to have that default value if they are not explicitly assigned a value when they are created.

如果 meetingDay 變數的類型是 Day,則 (不需要明確轉換) 您只能將 Day 所定義的其中一個值指派給它。If the variable meetingDay is of type Day, then (without an explicit cast) you can only assign it one of the values defined by Day. 如果會議日期變更,您可以指派新值,從 Day 變成 meetingDayAnd if the meeting day changes, you can assign a new value from Day to meetingDay:

Day meetingDay = Day.Monday;
//...
meetingDay = Day.Friday;

注意

您可以將任何任意整數值指派給 meetingDayIt's possible to assign any arbitrary integer value to meetingDay. 例如,這行程式碼不會產生錯誤︰meetingDay = (Day) 42For example, this line of code does not produce an error: meetingDay = (Day) 42. 不過,您不應該這麼做,因為隱含預期列舉變數只保留列舉定義的其中一個值。However, you should not do this because the implicit expectation is that an enum variable will only hold one of the values defined by the enum. 將任意值指派給列舉類型的變數會導致高風險錯誤。To assign an arbitrary value to a variable of an enumeration type is to introduce a high risk for errors.

您可以指派任何值給列舉類型的列舉程式清單中的項目,也可以使用計算的值︰You can assign any values to the elements in the enumerator list of an enumeration type, and you can also use computed values:

enum MachineState
{
    PowerOff = 0,
    Running = 5,
    Sleeping = 10,
    Hibernating = Sleeping + 5
}

作為位元旗標的列舉類型Enumeration types as bit flags

您可以使用列舉類型來定義位元旗標,讓列舉類型的執行個體儲存在列舉程式清單中所定義的任何值組。You can use an enumeration type to define bit flags, which enables an instance of the enumeration type to store any combination of the values that are defined in the enumerator list. (當然,某些組合在您的程式碼中可能無意義或不被允許。)(Of course, some combinations may not be meaningful or allowed in your program code.)

您可透過套用 System.FlagsAttribute 屬性和適當定義值來建立位元旗標列舉,以對它們執行 ANDORNOTXOR 位元運算。You create a bit flags enum by applying the System.FlagsAttribute attribute and defining the values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them. 在位元旗標列舉中包含值為零的具名常數,表示「未設定任何旗標」。In a bit flags enum, include a named constant with a value of zero that means "no flags are set." 如果不表示「未設定任何旗標」,請勿指定旗標值為零。Do not give a flag a value of zero if it does not mean "no flags are set".

在下例中,定義了另一個版本的 Day 列舉,名為 DaysIn the following example, another version of the Day enum, which is named Days, is defined. Days 具有 Flags 屬性,且每個值已指派下一個大於 2 的乘冪。Days has the Flags attribute, and each value is assigned the next greater power of 2. 這可讓您建立其值為 Days.Tuesday | Days.ThursdayDays 變數。This enables you to create a Days variable whose value is Days.Tuesday | Days.Thursday.

[Flags]
enum Days
{
    None      = 0b_0000_0000, // 0
    Sunday    = 0b_0000_0001, // 1
    Monday    = 0b_0000_0010, // 2
    Tuesday   = 0b_0000_0100, // 4
    Wednesday = 0b_0000_1000, // 8
    Thursday  = 0b_0001_0000, // 16
    Friday    = 0b_0010_0000, // 32
    Saturday  = 0b_0100_0000  // 64 
}
class MyClass
{
    Days meetingDays = Days.Tuesday | Days.Thursday;
}

若要對列舉設定旗標,請使用位元 OR 運算子,如下例所示︰To set a flag on an enum, use the bitwise OR operator as shown in the following example:

// Initialize with two flags using bitwise OR.
meetingDays = Days.Tuesday | Days.Thursday;

// Set an additional flag using bitwise OR.
meetingDays = meetingDays | Days.Friday;

Console.WriteLine($"Meeting days are {meetingDays}");
// Output: Meeting days are Tuesday, Thursday, Friday

// Toggle a flag using bitwise XOR.
meetingDays = meetingDays ^ Days.Tuesday;
Console.WriteLine($"Meeting days are {meetingDays}");
// Output: Meeting days are Thursday, Friday

若要判斷是否已設定特定的旗標,請使用位元 AND 作業,如下例所示︰To determine whether a specific flag is set, use a bitwise AND operation, as shown in the following example:

// Test value of flags using bitwise AND.
bool test = (meetingDays & Days.Thursday) == Days.Thursday;
Console.WriteLine($"Thursday {test == true ? "is" : "is not"} a meeting day.");
// Output: Thursday is a meeting day.

如需在定義含有 System.FlagsAttribute 屬性之列舉類型時需考量事項的詳細資訊,請參閱 System.EnumFor more information about what to consider when you define enumeration types with the System.FlagsAttribute attribute, see System.Enum.

使用 System.Enum 方法來探索和操作列舉值Using the System.Enum methods to discover and manipulate enum values

所有列舉都是 System.Enum 類型的執行個體。All enums are instances of the System.Enum type. 您不能從 System.Enum 衍生新的類別,但可以使用其方法來探索相關資訊以及操作列舉執行個體中的值。You cannot derive new classes from System.Enum, but you can use its methods to discover information about and manipulate values in an enum instance.

string s = Enum.GetName(typeof(Day), 4);
Console.WriteLine(s);

Console.WriteLine("The values of the Day Enum are:");
foreach (int i in Enum.GetValues(typeof(Day)))
    Console.WriteLine(i);

Console.WriteLine("The names of the Day Enum are:");
foreach (string str in Enum.GetNames(typeof(Day)))
    Console.WriteLine(str);

如需詳細資訊,請參閱 System.EnumFor more information, see System.Enum.

您也可以使用擴充方法,為列舉建立新的方法。You can also create a new method for an enum by using an extension method. 如需詳細資訊,請參閱如何:為列舉建立新方法For more information, see How to: Create a New Method for an Enumeration.

另請參閱See also