Enum 类

定义

为枚举提供基类。Provides the base class for enumerations.

public ref class Enum abstract : ValueType, IComparable, IConvertible, IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
type Enum = class
    inherit ValueType
    interface IComparable
    interface IFormattable
    interface IConvertible
Public MustInherit Class Enum
Inherits ValueType
Implements IComparable, IConvertible, 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. 如果没有显式声明基础类型,则使用 Int32If no underlying type is explicitly declared, Int32 is used. Enum 是 .NET Framework 中所有枚举的基类。Enum is the base class for all enumerations in the .NET Framework. 枚举类型由中C#的 enum 关键字定义,Visual Basic 中的 Enum...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. 有关详细信息,请参阅非独占成员和 Flags 属性部分和 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

警告

永远不应创建基础类型为非整型或 Char的枚举类型。You 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.OnTimeArrivalStatusThe 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.EarlyThe 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.

对于常量为位域的枚举类型,附加最佳方案在 "非独占成员" 和 "标志属性"部分中列出。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. 但是,枚举类型从 Enum 类继承一组完整的静态和实例方法。However, 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 方法以及实例 ToString 方法的重载,将枚举值转换为它们的字符串表示形式。You 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 实例的值可以是 EarlyOnTimeLateFor 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)      

定义按位枚举和应用 FlagsAttribute 属性时,应使用以下最佳实践。The following best practices should be used when defining a bitwise enumeration and applying the FlagsAttribute attribute.

  • 仅当对数值执行了按位运算(AND、OR、EXCLUSIVE 或)时,才将 FlagsAttribute 自定义属性用于枚举。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 = 1Write = 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. 此外,在某些情况下,用于合并标志的按位 "或" 运算在某些情况下可能被视为高级概念,而对于简单任务不是必需的。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.      
    

    它等效于在数值和标志枚举常量之间执行按位 "与" 运算,这会将数值中的所有位设置为零,而不是对应于标志,然后测试该操作的结果是否等于标记枚举常数。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 枚举常量来测试标志,因为结果始终为零。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))定义,因此不能为枚举类型定义自定义方法,而不是从 Enum 类继承的方法。Because 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.

GetNames(Type)

检索指定枚举中常数名称的数组。Retrieves an array of the names of the constants in a specified enumeration.

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.

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.

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)
Parse<TEnum>(String, Boolean)
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()
IConvertible.ToBoolean(IFormatProvider)

根据基础类型将当前值转换为布尔值。Converts the current value to a Boolean value based on the underlying type.

IConvertible.ToByte(IFormatProvider)

根据基础类型将当前值转换为 8 位无符号整数。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 位有符号整数。Converts the current value to a 16-bit signed integer based on the underlying type.

IConvertible.ToInt32(IFormatProvider)

根据基础类型将当前值转换为 32 位有符号整数。Converts the current value to a 32-bit signed integer based on the underlying type.

IConvertible.ToInt64(IFormatProvider)

根据基础类型将当前值转换为 64 位有符号整数。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)
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.

另请参阅