java mime类型的enum_Enum 类 (System) | Microsoft Docs

枚举(Enum)是.NET Framework中用于定义一组命名常量的类型,通常用于表示一组互斥的值。本文深入探讨了枚举的创建、实例化、操作、格式化和最佳实践,包括使用Flags属性来处理位字段枚举。示例代码展示了如何定义、转换、解析和遍历枚举成员,以及如何利用扩展方法为枚举类型添加功能。
摘要由CSDN通过智能技术生成

Enum 类

定义

程序集:System.Runtime.dll

程序集:mscorlib.dll, System.Runtime.dll

程序集:mscorlib.dll

程序集:netstandard.dll

为枚举提供基类。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

[]

type Enum = class

inherit ValueType

interface IComparable

interface IFormattable

interface IConvertible

[]

[]

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

_

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 End Enum Visual Basic 中的 ... 构造定义。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.

本主题内容:In this topic:

创建枚举类型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.Early 、 ArrivalStatus.OnTime 和 ArrivalStatus.Late 。It 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 值为的 ArrivalStatus.OnTime 。The 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)

通过调用 Parse 或 TryParse 方法来分析包含枚举中的常数名称的字符串。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. 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 1Dim 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

Parse和 TryParse 方法允许将枚举值的字符串表示形式转换为该值。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. The example illustrates this approach and demonstrates calls to both the Parse(Type, String) and Enum.TryParse(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(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 EarlyDim 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

// FFFFFFFFDim 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 类型不实现 IEnumerable 或 IEnumerable 接口,这使你可以使用 c # 中的 (来循环访问集合的成员 foreach ) 或 For Each Visual Basic) 构造中的 (。The Enum type does not implement the IEnumerable or IEnumerable 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 、或值 Late 。For 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 }; 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.

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 合并和标志的枚举常数 Read Write 。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

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 类的新实例。Initializes a new instance of the Enum class.

方法

将此实例与指定对象进行比较并返回一个对二者的相对值的指示。Compares this instance to a specified object and returns an indication of their relative values.

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

根据指定格式将指定枚举类型的指定值转换为其等效的字符串表示形式。Converts the specified value of a specified enumerated type to its equivalent string representation according to the specified format.

返回该实例的值的哈希代码。Returns the hash code for the value of this instance.

在指定枚举中检索具有指定值的常数的名称。Retrieves the name of the constant in the specified enumeration that has the specified value.

在指定枚举类型中检索具有指定值的常数的名称。Retrieves the name of the constant in the specified enumeration type that has the specified value.

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

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

获取当前实例的 Type。Gets the Type of the current instance.

(继承自 Object)

返回此枚举成员的基础类型的类型代码。Returns the type code of the underlying type of this enumeration member.

返回指定枚举的基础类型。Returns the underlying type of the specified enumeration.

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

检索指定枚举类型中常数值的数组。Retrieves an array of the values of the constants in a specified enumeration type.

确定当前实例中是否设置了一个或多个位域。Determines whether one or more bit fields are set in the current instance.

返回一个布尔值,该值指示给定的整数值或其名称字符串是否存在于指定的枚举中。Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

返回一个布尔值,该值指示给定的整数值或其名称字符串是否存在于指定的枚举中。Returns a boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。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.

将 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.

将 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.

将指定的 8 位无符号整数转换为枚举成员。Converts the specified 8-bit unsigned integer to an enumeration member.

将指定的 16 位有符号整数转换为枚举成员。Converts the specified 16-bit signed integer to an enumeration member.

将指定的 32 位有符号整数转换为枚举成员。Converts the specified 32-bit signed integer to an enumeration member.

将指定的 64 位有符号整数转换为枚举成员。Converts the specified 64-bit signed integer to an enumeration member.

将具有整数值的指定对象转换为枚举成员。Converts the specified object with an integer value to an enumeration member.

将指定的 8 位有符号整数值转换为枚举成员。Converts the specified 8-bit signed integer value to an enumeration member.

将指定的 16 位无符号整数值转换为枚举成员。Converts the specified 16-bit unsigned integer value to an enumeration member.

将指定的 32 位无符号整数值转换为枚举成员。Converts the specified 32-bit unsigned integer value to an enumeration member.

将指定的 64 位无符号整数值转换为枚举成员。Converts the specified 64-bit unsigned integer value to an enumeration member.

将此实例的值转换为其等效的字符串表示形式。Converts the value of this instance to its equivalent string representation.

已过时。

此方法重载已过时;请使用 ToString()。This method overload is obsolete; use ToString().

使用指定格式将此实例的值转换成其等效的字符串表示。Converts the value of this instance to its equivalent string representation using the specified format.

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。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.

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。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.

显式接口实现

返回此 Enum 实例的类型代码。Returns the type code of this Enum instance.

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

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

根据基础类型将当前值转换为 Unicode 字符。Converts the current value to a Unicode character based on the underlying type.

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

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

根据基础类型将当前值转换为双精度浮点数。Converts the current value to a double-precision floating point number based on the underlying type.

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

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

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

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

根据基础类型将当前值转换为单精度浮点数。Converts the current value to a single-precision floating-point number based on the underlying type.

已过时。

此方法重载已过时;请改用 ToString()。This method overload is obsolete; use ToString() instead.

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

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

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

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

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值