Enum 類別

定義

提供列舉的基底類別。Provides the base class for enumerations.

public ref class Enum abstract : ValueType, IComparable, IConvertible, IFormattable
public ref class Enum abstract : ValueType, IComparable, IFormattable
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
[System.Serializable]
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
public abstract class Enum : ValueType, IComparable, IFormattable
type Enum = class
    inherit ValueType
    interface IComparable
    interface IConvertible
    interface IFormattable
[<System.Serializable>]
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
    interface IConvertible
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IConvertible, IFormattable
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IFormattable
繼承
衍生
屬性
實作

範例

下列範例將示範如何使用列舉來代表命名值,並使用另一個列舉來表示已命名的位欄位。The following example demonstrates using an enumeration to represent named values and another enumeration to represent named bit fields.

using namespace System;
enum class Days
{
   Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
};

enum class BoilingPoints
{
   Celsius = 100,
   Fahrenheit = 212
};

[Flags]

enum class Colors
{
   Red = 1,
   Green = 2,
   Blue = 4,
   Yellow = 8
};

int main()
{
   Type^ weekdays = Days::typeid;
   Type^ boiling = BoilingPoints::typeid;
   Console::WriteLine(  "The days of the week, and their corresponding values in the Days Enum are:" );
   Array^ a = Enum::GetNames( weekdays );
   Int32 i = 0;
   do
   {
      Object^ o = a->GetValue( i );
      Console::WriteLine(  "{0,-11}= {1}", o->ToString(), Enum::Format( weekdays, Enum::Parse( weekdays, o->ToString() ),  "d" ) );
   }
   while ( ++i < a->Length );

   Console::WriteLine();
   Console::WriteLine(  "Enums can also be created which have values that represent some meaningful amount." );
   Console::WriteLine(  "The BoilingPoints Enum defines the following items, and corresponding values:" );
   i = 0;
   Array^ b = Enum::GetNames( boiling );
   do
   {
      Object^ o = b->GetValue( i );
      Console::WriteLine(  "{0,-11}= {1}", o->ToString(), Enum::Format( boiling, Enum::Parse( boiling, o->ToString() ),  "d" ) );
   }
   while ( ++i < b->Length );

   Array^ c = Enum::GetNames( Colors::typeid );
   Colors myColors = Colors::Red | Colors::Blue | Colors::Yellow;
   Console::WriteLine();
   Console::Write(  "myColors holds a combination of colors. Namely:" );
   for ( i = 0; i < 3; i++ )
      Console::Write(  " {0}", c->GetValue( i ) );
}
using System;

public class EnumTest {
    enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum BoilingPoints { Celsius = 100, Fahrenheit = 212 };
    [Flags]
    enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

    public static void Main() {

        Type weekdays = typeof(Days);
        Type boiling = typeof(BoilingPoints);

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:");

        foreach ( string s in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format( weekdays, Enum.Parse(weekdays, s), "d"));

        Console.WriteLine();
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.");
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:");

        foreach ( string s in Enum.GetNames(boiling) )
            Console.WriteLine( "{0,-11}= {1}", s, Enum.Format(boiling, Enum.Parse(boiling, s), "d"));

        Colors myColors = Colors.Red | Colors.Blue | Colors.Yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
    }
}
Public Class EnumTest
    Enum Days
        Saturday
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
    End Enum 
    
    Enum BoilingPoints
        Celsius = 100
        Fahrenheit = 212
    End Enum 
    
    <Flags()> _
    Enum Colors
        Red = 1
        Green = 2
        Blue = 4
        Yellow = 8
    End Enum 

    Public Shared Sub Main()
        Dim weekdays As Type = GetType(Days)
        Dim boiling As Type = GetType(BoilingPoints)

        Console.WriteLine("The days of the week, and their corresponding values in the Days Enum are:")

        Dim s As String
        For Each s In  [Enum].GetNames(weekdays)
            Console.WriteLine("{0,-11} = {1}", s, [Enum].Format(weekdays, [Enum].Parse(weekdays, s), "d"))
        
        Next s
        Console.WriteLine()
        Console.WriteLine("Enums can also be created which have values that represent some meaningful amount.")
        Console.WriteLine("The BoilingPoints Enum defines the following items, and corresponding values:")

        For Each s In  [Enum].GetNames(boiling)
            Console.WriteLine("{0,-11} = {1}", s, [Enum].Format(boiling, [Enum].Parse(boiling, s), "d"))
        Next s

        Dim myColors As Colors = Colors.Red Or Colors.Blue Or Colors.Yellow
        Console.WriteLine()
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors)
    End Sub 
End Class

備註

列舉是一組名為的常數,其基礎類型為任何整數類型。An enumeration is a set of named constants whose underlying type is any integral type. 如果未明確宣告任何基礎型別, Int32 則會使用。If no underlying type is explicitly declared, Int32 is used. Enum 是 .NET Framework 中所有列舉的基類。Enum is the base class for all enumerations in the .NET Framework. 列舉類型是由 enum c # 中的關鍵字和 Enum Visual Basic 中的 ... End Enum 結構定義。Enumeration types are defined by the enum keyword in C# and the Enum...End Enum construct in Visual Basic.

Enum 提供比較這個類別之實例的方法,將實例的值轉換為其字串標記法、將數位的字串表示轉換成這個類別的實例,以及建立指定列舉和值的實例。Enum provides methods for comparing instances of this class, converting the value of an instance to its string representation, converting the string representation of a number to an instance of this class, and creating an instance of a specified enumeration and value.

您也可以將列舉視為位欄位。You can also treat an enumeration as a bit field. 如需詳細資訊,請參閱 非獨佔成員和旗標屬性 一節和 FlagsAttribute 主題。For more information, see the Non-Exclusive Members and the Flags Attribute section and the FlagsAttribute topic.

本主題內容:In this topic:

建立列舉型別 Creating an enumeration type
具現化列舉型別 Instantiating an enumeration type
列舉的最佳作法 Enumeration best practices
使用列舉執行作業 Performing operations with enumerations
執行轉換Performing conversions
剖析列舉值Parsing enumeration values
格式化列舉值Formatting enumeration values
反覆運算列舉成員Iterating enumeration members
非獨佔成員和 Flags 屬性Non-exclusive members and the Flags attribute
新增列舉方法Adding enumeration methods

建立列舉型別Creating an enumeration type

程式設計語言通常會提供語法來宣告列舉,此列舉是由一組命名常數和其值所組成。Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values. 下列範例說明 c # 和 Visual Basic 用來定義列舉的語法。The following example illustrates the syntax used by C# and Visual Basic to define an enumeration. 它會建立名為 ArrivalStatus 的列舉,這個列舉有三個成員: ArrivalStatus.EarlyArrivalStatus.OnTimeArrivalStatus.LateIt creates an enumeration named ArrivalStatus that has three members: ArrivalStatus.Early, ArrivalStatus.OnTime, and ArrivalStatus.Late. 請注意,在這兩種情況下,列舉不會明確繼承自,而 Enum 繼承關聯性會由編譯器隱含處理。Note that in both cases, the enumeration does not explicitly inherit from Enum; the inheritance relationship is handled implicitly by the compiler.

public enum ArrivalStatus { Late=-1, OnTime=0, Early=1 };
Public Enum ArrivalStatus As Integer
   Late = -1
   OnTime = 0
   Early = 1
End Enum

警告

您絕對不應該建立其基礎類型為非整數或的列舉類型 CharYou should never create an enumeration type whose underlying type is non-integral or Char. 雖然您可以使用反映來建立這類列舉型別,但是使用結果型別的方法呼叫不可靠,也可能會擲回其他例外狀況。Although you can create such an enumeration type by using reflection, method calls that use the resulting type are unreliable and may also throw additional exceptions.

具現化列舉型別Instantiating an enumeration type

您可以具現化列舉型別,就像您具現化任何其他實值型別一樣:藉由宣告變數,並將其中一個列舉的常數指派給它。You can instantiate an enumeration type just as you instantiate any other value type: by declaring a variable and assigning one of the enumeration's constants to it. 下列範例 ArrivalStatus 會具現化值為的 ArrivalStatus.OnTimeThe following example instantiates an ArrivalStatus whose value is ArrivalStatus.OnTime.

public class Example
{
   public static void Main()
   {
      ArrivalStatus status = ArrivalStatus.OnTime;
      Console.WriteLine("Arrival Status: {0} ({0:D})", status);
   }
}
// The example displays the following output:
//       Arrival Status: OnTime (0)
Public Module Example
   Public Sub Main()
      Dim status As ArrivalStatus = ArrivalStatus.OnTime
      Console.WriteLine("Arrival Status: {0} ({0:D})", status)
   End Sub
End Module
' The example displays the following output:
'        Arrival Status: OnTime (0)

您也可以使用下列方式來具現化列舉值:You can also instantiate an enumeration value in the following ways:

  • 使用特定程式設計語言的功能,將 (轉換成 c # ) 或將 (轉換成 Visual Basic) 整數值轉換為列舉值。By using a particular programming language's features to cast (as in C#) or convert (as in Visual Basic) an integer value to an enumeration value. 下列範例 ArrivalStatus 會建立其值 ArrivalStatus.Early 以這種方式的物件。The following example creates an ArrivalStatus object whose value is ArrivalStatus.Early in this way.

    ArrivalStatus status2 = (ArrivalStatus) 1;
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2);
    // The example displays the following output:
    //       Arrival Status: Early (1)
    
    Dim status2 As ArrivalStatus = CType(1, ArrivalStatus)
    Console.WriteLine("Arrival Status: {0} ({0:D})", status2)
    ' The example displays the following output:
    '       Arrival Status: Early (1)
    
  • 藉由呼叫其隱含無參數的函式。By calling its implicit parameterless constructor. 如下列範例所示,在此案例中,列舉實例的基礎值為0。As the following example shows, in this case the underlying value of the enumeration instance is 0. 不過,這不一定是列舉中有效常數的值。However, this is not necessarily the value of a valid constant in the enumeration.

    ArrivalStatus status1 = new ArrivalStatus();
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1);
    // The example displays the following output:
    //       Arrival Status: OnTime (0)
    
    Dim status1 As New ArrivalStatus()
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1)
    ' The example displays the following output:
    '        Arrival Status: OnTime (0)
    
  • 藉由呼叫 ParseTryParse 方法,以剖析包含列舉中常數名稱的字串。By calling the Parse or TryParse method to parse a string that contains the name of a constant in the enumeration. 如需詳細資訊,請參閱 剖析列舉值 一節。For more information, see the Parsing Enumeration Values section.

  • 藉由呼叫 ToObject 方法,將整數值轉換為列舉型別。By calling the ToObject method to convert an integral value to an enumeration type. 如需詳細資訊,請參閱 執行轉換 一節。For more information, see the Performing Conversions section.

列舉的最佳作法Enumeration best practices

當您定義列舉類型時,建議您使用下列最佳作法:We recommend that you use the following best practices when you define enumeration types:

  • 如果您未定義其值為0的列舉成員,請考慮建立 None 列舉常數。If you have not defined an enumeration member whose value is 0, consider creating a None enumerated constant. 根據預設,通用語言執行時間會將用於列舉的記憶體初始化為零。By default, the memory used for the enumeration is initialized to zero by the common language runtime. 因此,如果您未定義其值為零的常數,則在建立時,列舉會包含不合法的值。Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created.

  • 如果您的應用程式必須呈現明顯的預設案例,請考慮使用值為零的列舉常數來表示它。If there is an obvious default case that your application has to represent, consider using an enumerated constant whose value is zero to represent it. 如果沒有預設案例,請考慮使用值為零的列舉常數,指定不是由其他任何列舉常數所表示的大小寫。If there is no default case, consider using an enumerated constant whose value is zero to specify the case that is not represented by any of the other enumerated constants.

  • 請勿指定保留給未來使用的列舉常數。Do not specify enumerated constants that are reserved for future use.

  • 當您定義採用列舉常數作為值的方法或屬性時,請考慮驗證值。When you define a method or property that takes an enumerated constant as a value, consider validating the value. 原因是,您可以將數值轉換成列舉型別,即使該數值未在列舉中定義。The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration.

列舉類型的其他最佳做法(其常數為位欄位)會列在 非獨佔成員和 Flags 屬性 區段中。Additional best practices for enumeration types whose constants are bit fields are listed in the Non-Exclusive Members and the Flags Attribute section.

使用列舉執行作業Performing operations with enumerations

當您建立列舉時,無法定義新的方法。You cannot define new methods when you are creating an enumeration. 不過,列舉型別會從類別繼承一組完整的靜態和實例方法 EnumHowever, an enumeration type inherits a complete set of static and instance methods from the Enum class. 下列各節將討論這些方法的大部分,以及使用列舉值時常見使用的數個其他方法。The following sections survey most of these methods, in addition to several other methods that are commonly used when working with enumeration values.

執行轉換Performing conversions

您可以使用 c ) # 中的轉型 (,或 Visual Basic) 運算子中的轉換 (,在列舉成員與其基礎型別之間進行轉換。You can convert between an enumeration member and its underlying type by using a casting (in C#) or conversion (in Visual Basic) operator. 下列範例會使用轉型或轉換運算子,從整數轉換成列舉值,以及從列舉值轉換為整數。The following example uses casting or conversion operators to perform conversions both from an integer to an enumeration value and from an enumeration value to an integer.

int value3 = 2;
ArrivalStatus status3 = (ArrivalStatus) value3;

int value4 = (int) status3;
Dim value3 As Integer = 2
Dim status3 As ArrivalStatus = CType(value3, ArrivalStatus)

Dim value4 As Integer = CInt(status3)

Enum類別也包含 ToObject 將任何整數類資料類型的值轉換成列舉值的方法。The Enum class also includes a ToObject method that converts a value of any integral type to an enumeration value. 下列範例會使用 ToObject(Type, Int32) 方法,將轉換成 Int32 ArrivalStatus 值。The following example uses the ToObject(Type, Int32) method to convert an Int32 to an ArrivalStatus value. 請注意,因為 ToObject 會傳回型別的值 Object ,所以可能仍需要使用轉型或轉換運算子來將物件轉換成列舉型別。Note that, because the ToObject returns a value of type Object, the use of a casting or conversion operator may still be necessary to cast the object to the enumeration type.

int number = -1;
ArrivalStatus arrived = (ArrivalStatus) ArrivalStatus.ToObject(typeof(ArrivalStatus), number);
Dim number As Integer = -1
Dim arrived As ArrivalStatus = CType(ArrivalStatus.ToObject(GetType(ArrivalStatus), number), ArrivalStatus)

將整數轉換為列舉值時,可能會指派不是實際列舉成員的值。When converting an integer to an enumeration value, it is possible to assign a value that is not actually a member of the enumeration. 若要避免這種情況,您可以在執行轉換之前將整數傳遞給 IsDefined 方法。To prevent this, you can pass the integer to the IsDefined method before performing the conversion. 下列範例會使用這個方法來判斷整數值陣列中的元素是否可以轉換成 ArrivalStatus 值。The following example uses this method to determine whether the elements in an array of integer values can be converted to ArrivalStatus values.

using System;

public enum ArrivalStatus { Unknown=-3, Late=-1, OnTime=0, Early=1 };

public class Example
{
   public static void Main()
   {
      int[] values = { -3, -1, 0, 1, 5, Int32.MaxValue };
      foreach (var value in values)
      {
         ArrivalStatus status;
         if (Enum.IsDefined(typeof(ArrivalStatus), value))
            status = (ArrivalStatus) value;
         else
            status = ArrivalStatus.Unknown;
         Console.WriteLine("Converted {0:N0} to {1}", value, status);
      }
   }
}
// The example displays the following output:
//       Converted -3 to Unknown
//       Converted -1 to Late
//       Converted 0 to OnTime
//       Converted 1 to Early
//       Converted 5 to Unknown
//       Converted 2,147,483,647 to Unknown
Public Enum ArrivalStatus As Integer
   Unknown = -3
   Late = -1
   OnTime = 0
   Early = 1
End Enum

Module Example
   Public Sub Main()
      Dim values() As Integer = { -3, -1, 0, 1, 5, Int32.MaxValue }
      For Each value In values
         Dim status As ArrivalStatus
         If [Enum].IsDefined(GetType(ArrivalStatus), value)
            status = CType(value, ArrivalStatus) 
         Else
            status = ArrivalStatus.Unknown
         End If
         Console.WriteLine("Converted {0:N0} to {1}", value, status)
      Next   
   End Sub
End Module
' The example displays the following output:
'       Converted -3 to Unknown
'       Converted -1 to Late
'       Converted 0 to OnTime
'       Converted 1 to Early
'       Converted 5 to Unknown
'       Converted 2,147,483,647 to Unknown

雖然 Enum 類別會提供介面的明確介面介面, IConvertible 以便從列舉值轉換為整數類資料類型,但您應該使用類別的方法( Convert 例如 ToInt32 )來執行這些轉換。Although the Enum class provides explicit interface implementations of the IConvertible interface for converting from an enumeration value to an integral type, you should use the methods of the Convert class, such as ToInt32, to perform these conversions. 下列範例說明如何 GetUnderlyingType 搭配方法使用方法 Convert.ChangeType ,以將列舉值轉換為其基礎類型。The following example illustrates how you can use the GetUnderlyingType method along with the Convert.ChangeType method to convert an enumeration value to its underlying type. 請注意,此範例不需要在編譯時期知道列舉的基礎類型。Note that this example does not require the underlying type of the enumeration to be known at compile time.

ArrivalStatus status = ArrivalStatus.Early;
var number = Convert.ChangeType(status, Enum.GetUnderlyingType(typeof(ArrivalStatus)));
Console.WriteLine("Converted {0} to {1}", status, number);
// The example displays the following output:
//       Converted Early to 1
Dim status As ArrivalStatus = ArrivalStatus.Early
Dim number = Convert.ChangeType(status, [Enum].GetUnderlyingType(GetType(ArrivalStatus)))
Console.WriteLine("Converted {0} to {1}", status, number)
' The example displays the following output:
'       Converted Early to 1

剖析列舉值Parsing enumeration values

ParseTryParse 方法可讓您將列舉值的字串表示轉換為該值。The Parse and TryParse methods allow you to convert the string representation of an enumeration value to that value. 字串表示可以是列舉常數的名稱或基礎值。The string representation can be either the name or the underlying value of an enumeration constant. 請注意,如果字串可以轉換成列舉的基礎類型的值,則剖析方法會成功轉換非特定列舉成員之數位的字串表示。Note that the parsing methods will successfully convert string representations of numbers that are not members of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. 為了避免這種情況,您 IsDefined 可以呼叫方法,以確保剖析方法的結果是有效的列舉值。To prevent this, the IsDefined method can be called to ensure that the result of the parsing method is a valid enumeration value. 此範例將說明這種方法,並示範對 Parse(Type, String)Enum.TryParse<TEnum>(String, TEnum) 方法的呼叫。The example illustrates this approach and demonstrates calls to both the Parse(Type, String) and Enum.TryParse<TEnum>(String, TEnum) methods. 請注意,非泛型剖析方法會傳回您可能必須將 (轉換成 c # ) 或將 Visual Basic) 中的 (轉換為適當列舉型別的物件。Note that the non-generic parsing method returns an object that you may have to cast (in C#) or convert (in Visual Basic) to the appropriate enumeration type.

string number = "-1";
string name = "Early";

try {
   ArrivalStatus status1 = (ArrivalStatus) Enum.Parse(typeof(ArrivalStatus), number);
   if (!(Enum.IsDefined(typeof(ArrivalStatus), status1)))
      status1 = ArrivalStatus.Unknown;
   Console.WriteLine("Converted '{0}' to {1}", number, status1);
}
catch (FormatException) {
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.",
                     number);
}

ArrivalStatus status2;
if (Enum.TryParse<ArrivalStatus>(name, out status2)) {
   if (!(Enum.IsDefined(typeof(ArrivalStatus), status2)))
      status2 = ArrivalStatus.Unknown;
   Console.WriteLine("Converted '{0}' to {1}", name, status2);
}
else {
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.",
                     number);
}
// The example displays the following output:
//       Converted '-1' to Late
//       Converted 'Early' to Early
Dim number As String = "-1"
Dim name As String = "Early"
Dim invalid As String = "32"

Try 
   Dim status1 As ArrivalStatus = CType([Enum].Parse(GetType(ArrivalStatus), number), ArrivalStatus)
   If Not [Enum].IsDefined(GetType(ArrivalStatus), status1) Then status1 = ArrivalStatus.Unknown
   Console.WriteLine("Converted '{0}' to {1}", number, status1)
Catch e As FormatException
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number)
End Try   
   
Dim status2 As ArrivalStatus
If [Enum].TryParse(Of ArrivalStatus)(name, status2) Then
   If Not [Enum].IsDefined(GetType(ArrivalStatus), status2) Then status2 = ArrivalStatus.Unknown
   Console.WriteLine("Converted '{0}' to {1}", name, status2)
Else
   Console.WriteLine("Unable to convert '{0}' to an ArrivalStatus value.", 
                     number)
End If
' The example displays the following output:
'       Converted '-1' to Late
'       Converted 'Early' to Early

格式化列舉值Formatting enumeration values

您可以藉由呼叫靜態方法和實例方法的多載,將列舉值轉換為其字串表示 Format ToStringYou can convert enumeration values to their string representations by calling the static Format method, as well as the overloads of the instance ToString method. 您可以使用格式字串來控制列舉值以字串表示的精確方式。You can use a format string to control the precise way in which an enumeration value is represented as a string. 如需詳細資訊,請參閱 列舉格式字串For more information, see Enumeration Format Strings. 下列範例會使用每個支援的列舉格式字串 ( "G" 或 "g"、"D"、"d"、"X" 或 "x",以及 "F" 或 "f" ) 將列舉的成員轉換 ArrivalStatus 為其字串表示。The following example uses each of the supported enumeration format strings ("G" or "g", "D" or "d", "X" or "x", and "F" or "f" ) to convert a member of the ArrivalStatus enumeration to its string representations.

string[] formats= { "G", "F", "D", "X"};
ArrivalStatus status = ArrivalStatus.Late;
foreach (var fmt in formats)
   Console.WriteLine(status.ToString(fmt));

// The example displays the following output:
//       Late
//       Late
//       -1
//       FFFFFFFF
Dim formats() As String = { "G", "F", "D", "X"}
Dim status As ArrivalStatus = ArrivalStatus.Late
For Each fmt As String In formats
   Console.WriteLine(status.ToString(fmt))
Next
' The example displays the following output:
'       Late
'       Late
'       -1
'       FFFFFFFF

反覆運算列舉成員Iterating enumeration members

型別不 Enum 會執行 IEnumerableIEnumerable<T> 介面,這可讓您使用 foreach c # ) 中的 (或 For Each Visual Basic) 結構中的 (,逐一查看集合的成員。The Enum type does not implement the IEnumerable or IEnumerable<T> interface, which would enable you to iterate members of a collection by using a foreach (in C#) or For Each (in Visual Basic) construct. 不過,您可以透過下列兩種方式之一來列舉成員。However, you can enumerate members in either of two ways.

  • 您可以呼叫 GetNames 方法,以取得包含列舉成員名稱的字串陣列。You can call the GetNames method to retrieve a string array containing the names of the enumeration members. 接下來,針對字串陣列的每個元素,您可以呼叫 Parse 方法,將字串轉換為其相等的列舉值。Next, for each element of the string array, you can call the Parse method to convert the string to its equivalent enumeration value. 下列範例將示範這個方法。The following example illustrates this approach.

    string[] names = Enum.GetNames(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    Array.Sort(names);
    foreach (var name in names) {
       ArrivalStatus status = (ArrivalStatus) Enum.Parse(typeof(ArrivalStatus), name);
       Console.WriteLine("   {0} ({0:D})", status);
    }
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          Early (1)
    //          Late (-1)
    //          OnTime (0)
    //          Unknown (-3)
    
    Dim names() As String = [Enum].GetNames(GetType(ArrivalStatus))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus).Name)
    Array.Sort(names)
    For Each name In names
       Dim status As ArrivalStatus = CType([Enum].Parse(GetType(ArrivalStatus), name),
                                     ArrivalStatus)
       Console.WriteLine("   {0} ({0:D})", status)
    Next
    ' The example displays the following output:
    '       Members of ArrivalStatus:
    '          Early (1)
    '          Late (-1)
    '          OnTime (0)
    '          Unknown (-3)      
    
  • 您可以呼叫 GetValues 方法,以取得包含列舉中基礎值的陣列。You can call the GetValues method to retrieve an array that contains the underlying values in the enumeration. 接下來,針對陣列的每個元素,您可以呼叫 ToObject 方法,將整數轉換為其相等的列舉值。Next, for each element of the array, you can call the ToObject method to convert the integer to its equivalent enumeration value. 下列範例將示範這個方法。The following example illustrates this approach.

    var values = Enum.GetValues(typeof(ArrivalStatus));
    Console.WriteLine("Members of {0}:", typeof(ArrivalStatus).Name);
    foreach (ArrivalStatus status in values) {
       Console.WriteLine("   {0} ({0:D})", status);
    }
    // The example displays the following output:
    //       Members of ArrivalStatus:
    //          OnTime (0)
    //          Early (1)
    //          Unknown (-3)
    //          Late (-1)
    
    Dim values = [Enum].GetValues(GetType(ArrivalStatus))
    Console.WriteLine("Members of {0}:", GetType(ArrivalStatus).Name)
    For Each value In values
       Dim status As ArrivalStatus = CType([Enum].ToObject(GetType(ArrivalStatus), value),
                                           ArrivalStatus)
       Console.WriteLine("   {0} ({0:D})", status)
    Next                                       
    ' The example displays the following output:
    '       Members of ArrivalStatus:
    '          OnTime (0)
    '          Early (1)
    '          Unknown (-3)
    '          Late (-1)
    

非獨佔成員和 Flags 屬性Non-exclusive members and the Flags attribute

列舉的其中一個常見用法是表示一組互斥的值。One common use of an enumeration is to represent a set of mutually exclusive values. 例如, ArrivalStatus 實例可以具有 Early 、或的值 OnTime LateFor example, an ArrivalStatus instance can have a value of Early, OnTime, or Late. 實例的值不會 ArrivalStatus 反映一個以上的列舉常數。It makes no sense for the value of an ArrivalStatus instance to reflect more than one enumeration constant.

不過,在其他情況下,列舉物件的值可以包含多個列舉成員,而每個成員都代表列舉值中的位欄位。In other cases, however, the value of an enumeration object can include multiple enumeration members, and each member represents a bit field in the enumeration value. FlagsAttribute屬性可以用來表示列舉是由位欄位所組成。The FlagsAttribute attribute can be used to indicate that the enumeration consists of bit fields. 例如,名為的列舉 Pets 可能用來表示家庭中的寵物種類。For example, an enumeration named Pets might be used to indicate the kinds of pets in a household. 您可以依照下列方式定義它。It can be defined as follows.

[Flags] public enum Pets { None=0, Dog=1, Cat=2, Bird=4, Rodent=8,
                           Reptile=16, Other=32 };

<Flags> Public Enum Pets As Integer
   None = 0
   Dog = 1
   Cat = 2
   Bird = 4
   Rodent = 8
   Reptile = 16
   Other = 32
End Enum

Pets然後可以使用列舉,如下列範例所示。The Pets enumeration can then be used as shown in the following example.

Pets familyPets = Pets.Dog | Pets.Cat;
Console.WriteLine("Pets: {0:G} ({0:D})", familyPets);
// The example displays the following output:
//       Pets: Dog, Cat (3)
Dim familyPets As Pets = Pets.Dog Or Pets.Cat
Console.WriteLine("Pets: {0:G} ({0:D})", familyPets)
' The example displays the following output:
'       Pets: Dog, Cat (3)      

定義位列舉並套用屬性時,應該使用下列最佳作法 FlagsAttributeThe following best practices should be used when defining a bitwise enumeration and applying the FlagsAttribute attribute.

  • FlagsAttribute只有當位運算 (and、or、EXCLUSIVE 或) 是在數值上執行時,才使用自訂屬性做為列舉。Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

  • 將列舉常數定義為2的乘冪,也就是1、2、4、8等等。Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. 這表示結合的列舉常數中的個別旗標不會重迭。This means the individual flags in combined enumeration constants do not overlap.

  • 請考慮建立常用旗標組合的列舉常數。Consider creating an enumerated constant for commonly used flag combinations. 例如,如果您有一個用於包含列舉常數和之檔案 i/o 作業的列舉 Read = 1 Write = 2 ,請考慮建立列舉常數 ReadWrite = Read OR Write ,其中結合了 ReadWrite 旗標。For example, if you have an enumeration used for file I/O operations that contains the enumerated constants Read = 1 and Write = 2, consider creating the enumerated constant ReadWrite = Read OR Write, which combines the Read and Write flags. 此外,在某些情況下,用來結合旗標的位 OR 運算可能會被視為一種簡單的概念。In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks.

  • 如果您定義負數作為旗標列舉常數,因為有許多旗標位置可能設定為1,這可能會讓您的程式碼變得令人困惑,並鼓勵程式碼錯誤,請務必謹慎使用。Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors.

  • 測試旗標是否設定在數值中的方便方式,就是呼叫實例 HasFlag 方法,如下列範例所示。A convenient way to test whether a flag is set in a numeric value is to call the instance HasFlag method, as shown in the following example.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets.HasFlag(Pets.Dog))
       Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets.HasFlag(Pets.Dog) Then
       Console.WriteLine("The family has a dog.")
    End If
    ' The example displays the following output:
    '       The family has a dog.      
    

    它相當於在數值和旗標列舉常數之間執行位 AND 運算,這會將數值中的所有位設定為零,而不會對應至旗標,然後測試該運算的結果是否等於旗標列舉常數。It is equivalent to performing a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, and then testing whether the result of that operation is equal to the flag enumerated constant. 下列範例會加以說明。This is illustrated in the following example.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if ((familyPets & Pets.Dog) == Pets.Dog)
       Console.WriteLine("The family has a dog.");
    // The example displays the following output:
    //       The family has a dog.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets And Pets.Dog = Pets.Dog Then
       Console.WriteLine("The family has a dog.")
    End If   
    ' The example displays the following output:
    '       The family has a dog.      
    
  • 用作 None 值為零之旗標列舉常數的名稱。Use None as the name of the flag enumerated constant whose value is zero. 您無法使用 None 位 and 運算中的列舉常數來測試旗標,因為結果一律為零。You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. 不過,您可以在數值和列舉常數之間執行邏輯(而非位比較), None 以判斷是否已設定數值中的任何位。However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. 下列範例會加以說明。This is illustrated in the following example.

    Pets familyPets = Pets.Dog | Pets.Cat;
    if (familyPets == Pets.None)
       Console.WriteLine("The family has no pets.");
    else
       Console.WriteLine("The family has pets.");
    // The example displays the following output:
    //       The family has pets.
    
    Dim familyPets As Pets = Pets.Dog Or Pets.Cat
    If familyPets = Pets.None Then
       Console.WriteLine("The family has no pets.")
    Else
       Console.WriteLine("The family has pets.")   
    End If
    ' The example displays the following output:
    '       The family has pets.      
    
  • 請勿只定義列舉值來鏡像列舉本身的狀態。Do not define an enumeration value solely to mirror the state of the enumeration itself. 例如,請勿定義只標示列舉結尾的列舉常數。For example, do not define an enumerated constant that merely marks the end of the enumeration. 如果您需要判斷列舉的最後一個值,請明確檢查該值。If you need to determine the last value of the enumeration, check for that value explicitly. 此外,如果範圍內的所有值都有效,您可以針對第一個和最後一個列舉的常數執行範圍檢查。In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid.

新增列舉方法Adding enumeration methods

因為列舉型別是由語言結構所定義,例如 enum (c # ) 和 Enum (Visual Basic) ,所以您無法針對從類別繼承的方法,定義列舉型別的自訂方法 EnumBecause enumeration types are defined by language structures, such as enum (C#) and Enum (Visual Basic), you cannot define custom methods for an enumeration type other than those methods inherited from the Enum class. 不過,您可以使用擴充方法,將功能新增至特定列舉型別。However, you can use extension methods to add functionality to a particular enumeration type.

在下例中,Grades 列舉代表班上學生可能得到的字母分級成績。In the following example, the Grades enumeration represents the possible letter grades that a student may receive in a class. 已將名為 Passing 的擴充方法新增至 Grades 類型,以便該類型的每個執行個體現在都「知道」它是否代表傳遞等級。An extension method named Passing is added to the Grades type so that each instance of that type now "knows" whether it represents a passing grade or not. Extensions 類別也包含可定義最低傳遞等級的靜態讀寫變數。The Extensions class also contains a static read-write variable that defines the minimum passing grade. 擴充方法的傳回值 Passing 會反映該變數目前的值。The return value of the Passing extension method reflects the current value of that variable.

using System;

// Define an enumeration to represent student grades.
public enum Grades { F = 0, D = 1, C = 2, B = 3, A = 4 };

// Define an extension method for the Grades enumeration.
public static class Extensions
{
  public static Grades minPassing = Grades.D;

  public static bool Passing(this Grades grade)
  {
      return grade >= minPassing;
  }
}

class Example
{
  static void Main()
  {
      Grades g1 = Grades.D;
      Grades g2 = Grades.F;
      Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not");
      Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not");

      Extensions.minPassing = Grades.C;
      Console.WriteLine("\nRaising the bar!\n");
      Console.WriteLine("{0} {1} a passing grade.", g1, g1.Passing() ? "is" : "is not");
      Console.WriteLine("{0} {1} a passing grade.", g2, g2.Passing() ? "is" : "is not");
  }
}
// The exmaple displays the following output:
//       D is a passing grade.
//       F is not a passing grade.
//
//       Raising the bar!
//
//       D is not a passing grade.
//       F is not a passing grade.
Imports System.Runtime.CompilerServices

' Define an enumeration to represent student grades.
Public Enum Grades As Integer
   F = 0
   D = 1
   C = 2
   B = 3
   A = 4
End Enum   

' Define an extension method for the Grades enumeration.
Public Module Extensions
  Public minPassing As Grades = Grades.D
 
  <Extension>
  Public Function Passing(grade As Grades) As Boolean
     Return grade >= minPassing
  End Function
End Module

Public Module Example
  Public Sub Main()
      Dim g1 As Grades = Grades.D
      Dim g2 As Grades = Grades.F
      Console.WriteLine("{0} {1} a passing grade.", 
                        g1, If(g1.Passing(), "is", "is not"))
      Console.WriteLine("{0} {1} a passing grade.", 
                        g2, If(g2.Passing(), "is", "is not"))
      Console.WriteLine()
      
      Extensions.minPassing = Grades.C
      Console.WriteLine("Raising the bar!")
      Console.WriteLine()
      Console.WriteLine("{0} {1} a passing grade.", 
                        g1, If(g1.Passing(), "is", "is not"))
      Console.WriteLine("{0} {1} a passing grade.", 
                        g2, If(g2.Passing(), "is", "is not"))
  End Sub
End Module
' The exmaple displays the following output:
'       D is a passing grade.
'       F is not a passing grade.
'       
'       Raising the bar!
'       
'       D is not a passing grade.
'       F is not a passing grade.

建構函式

Enum()

初始化 Enum 類別的新執行個體。Initializes a new instance of the Enum class.

方法

CompareTo(Object)

將這個執行個體與指定的物件相比較,並傳回它們的相對值指示。Compares this instance to a specified object and returns an indication of their relative values.

Equals(Object)

傳回值,該值表示這個執行個體是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

Format(Type, Object, String)

根據指定的格式,將指定列舉類型的指定值轉換為相等的字串表示。Converts the specified value of a specified enumerated type to its equivalent string representation according to the specified format.

GetHashCode()

傳回這個執行個體值的雜湊碼。Returns the hash code for the value of this instance.

GetName(Type, Object)

擷取有指定數值之指定列舉的常數名稱。Retrieves the name of the constant in the specified enumeration that has the specified value.

GetName<TEnum>(TEnum)

在具有指定數值的指定列舉類型中擷取常數名稱。Retrieves the name of the constant in the specified enumeration type that has the specified value.

GetNames(Type)

在指定的列舉中擷取常數名稱的陣列。Retrieves an array of the names of the constants in a specified enumeration.

GetNames<TEnum>()

在指定的列舉類型中擷取常數名稱的陣列。Retrieves an array of the names of the constants in a specified enumeration type.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
GetTypeCode()

傳回這個列舉成員的基礎類型的類型代碼。Returns the type code of the underlying type of this enumeration member.

GetUnderlyingType(Type)

傳回指定列舉的基礎類型。Returns the underlying type of the specified enumeration.

GetValues(Type)

在指定的列舉中擷取常數值的陣列。Retrieves an array of the values of the constants in a specified enumeration.

GetValues<TEnum>()

在指定的列舉類型中擷取常數值的陣列。Retrieves an array of the values of the constants in a specified enumeration type.

HasFlag(Enum)

判斷目前執行個體中是否設定一或多個位元欄位。Determines whether one or more bit fields are set in the current instance.

IsDefined(Type, Object)

傳回布林值,告知指定整數值或其作為字串的名稱,是否存在於指定的列舉中。Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

IsDefined<TEnum>(TEnum)

傳回布林值,告知指定整數值或其作為字串的名稱,是否存在於指定的列舉中。Returns a boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
Parse(Type, String)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Parse(Type, String, Boolean)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 參數會定義運算是否區分大小寫。A parameter specifies whether the operation is case-insensitive.

Parse<TEnum>(String)

將一或多個列舉常數的名稱或數值字串表示 (由 TEnum 所指定) 轉換為相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object.

Parse<TEnum>(String, Boolean)

將一或多個列舉常數的名稱或數值字串表示 (由 TEnum 所指定) 轉換為相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. 參數會定義運算是否區分大小寫。A parameter specifies whether the operation is case-insensitive.

ToObject(Type, Byte)

將指定的 8 位元不帶正負號的整數轉換為列舉成員。Converts the specified 8-bit unsigned integer to an enumeration member.

ToObject(Type, Int16)

將指定的 16 位元帶正負號的整數轉換為列舉成員。Converts the specified 16-bit signed integer to an enumeration member.

ToObject(Type, Int32)

將指定的 32 位元帶正負號的整數轉換為列舉成員。Converts the specified 32-bit signed integer to an enumeration member.

ToObject(Type, Int64)

將指定的 64 位元帶正負號的整數轉換為列舉成員。Converts the specified 64-bit signed integer to an enumeration member.

ToObject(Type, Object)

將具有整數值的指定物件轉換為列舉成員。Converts the specified object with an integer value to an enumeration member.

ToObject(Type, SByte)

將指定的 8 位元帶正負號的整數值轉換為列舉成員。Converts the specified 8-bit signed integer value to an enumeration member.

ToObject(Type, UInt16)

將指定的 16 位元不帶正負號的整數值轉換為列舉成員。Converts the specified 16-bit unsigned integer value to an enumeration member.

ToObject(Type, UInt32)

將指定的 32 位元不帶正負號的整數值轉換為列舉成員。Converts the specified 32-bit unsigned integer value to an enumeration member.

ToObject(Type, UInt64)

將指定的 64 位元不帶正負號的整數值轉換為列舉成員。Converts the specified 64-bit unsigned integer value to an enumeration member.

ToString()

將這個執行個體的值轉換為它的相等字串表示。Converts the value of this instance to its equivalent string representation.

ToString(IFormatProvider)
已過時。

這個方法多載已淘汰,請改用 ToString()This method overload is obsolete; use ToString().

ToString(String)

使用指定格式,將這個執行個體的值轉換為它的相等字串表示。Converts the value of this instance to its equivalent string representation using the specified format.

ToString(String, IFormatProvider)
已過時。

這個方法多載已淘汰,請改用 ToString(String)This method overload is obsolete; use ToString(String).

TryParse(Type, String, Boolean, Object)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse(Type, String, Object)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse<TEnum>(String, Boolean, TEnum)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 參數會指定運算是否區分大小寫。A parameter specifies whether the operation is case-sensitive. 指出轉換是否成功的傳回值。The return value indicates whether the conversion succeeded.

TryParse<TEnum>(String, TEnum)

把一或多個列舉常數的名稱或數值的字串表示轉換為一個相等列舉物件。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 指出轉換是否成功的傳回值。The return value indicates whether the conversion succeeded.

明確介面實作

IConvertible.GetTypeCode()

傳回這個 Enum 執行個體的類型代碼。Returns the type code of this Enum instance.

IConvertible.ToBoolean(IFormatProvider)

根據基礎類型,將目前值轉換成布林值 (Boolean)。Converts the current value to a Boolean value based on the underlying type.

IConvertible.ToByte(IFormatProvider)

根據基礎類型,將目前值轉換成 8 位元不帶正負號的整數 (Unsigned Integer)。Converts the current value to an 8-bit unsigned integer based on the underlying type.

IConvertible.ToChar(IFormatProvider)

根據基礎類型,將目前值轉換成 Unicode 字元。Converts the current value to a Unicode character based on the underlying type.

IConvertible.ToDateTime(IFormatProvider)

根據基礎類型,將目前值轉換成 DateTimeConverts the current value to a DateTime based on the underlying type.

IConvertible.ToDecimal(IFormatProvider)

根據基礎類型,將目前值轉換成 DecimalConverts the current value to a Decimal based on the underlying type.

IConvertible.ToDouble(IFormatProvider)

根據基礎類型,將目前值轉換成雙精確度浮點數。Converts the current value to a double-precision floating point number based on the underlying type.

IConvertible.ToInt16(IFormatProvider)

根據基礎類型,將目前值轉換成 16 位元帶正負號的整數 (Signed Integer)。Converts the current value to a 16-bit signed integer based on the underlying type.

IConvertible.ToInt32(IFormatProvider)

根據基礎類型,將目前值轉換成 32 位元帶正負號的整數 (Signed Integer)。Converts the current value to a 32-bit signed integer based on the underlying type.

IConvertible.ToInt64(IFormatProvider)

根據基礎類型,將目前值轉換成 64 位元帶正負號的整數 (Signed Integer)。Converts the current value to a 64-bit signed integer based on the underlying type.

IConvertible.ToSByte(IFormatProvider)

根據基礎類型,將目前值轉換成 8 位元帶正負號的整數。Converts the current value to an 8-bit signed integer based on the underlying type.

IConvertible.ToSingle(IFormatProvider)

根據基礎類型,將目前值轉換成單精確度浮點數。Converts the current value to a single-precision floating-point number based on the underlying type.

IConvertible.ToString(IFormatProvider)
已過時。

這個方法多載已淘汰,請改用 ToString()This method overload is obsolete; use ToString() instead.

IConvertible.ToType(Type, IFormatProvider)

根據基礎類型,將目前值轉換成指定的類型。Converts the current value to a specified type based on the underlying type.

IConvertible.ToUInt16(IFormatProvider)

根據基礎類型,將目前值轉換成 16 位元不帶正負號的整數。Converts the current value to a 16-bit unsigned integer based on the underlying type.

IConvertible.ToUInt32(IFormatProvider)

根據基礎類型,將目前值轉換成 32 位元不帶正負號的整數。Converts the current value to a 32-bit unsigned integer based on the underlying type.

IConvertible.ToUInt64(IFormatProvider)

根據基礎類型,將目前值轉換成 64 位元不帶正負號的整數。Converts the current value to a 64-bit unsigned integer based on the underlying type.

IFormattable.ToString(String, IFormatProvider)
已過時。

這個方法多載已淘汰,請改用 ToString(String)This method overload is obsolete; use ToString(String).

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱