Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

Enum-Klasse

 

Veröffentlicht: Oktober 2016

Stellt die Basisklasse für Enumerationen bereit.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)


<SerializableAttribute>
<ComVisibleAttribute(True)>
Public MustInherit Class Enum
	Inherits ValueType
	Implements IComparable, IFormattable, IConvertible

NameBeschreibung
System_CAPS_protmethodEnum()

Initialisiert eine neue Instanz der Enum-Klasse.

NameBeschreibung
System_CAPS_pubmethodCompareTo(Object)

Vergleicht diese Instanz mit einem angegebenen Objekt und gibt eine Angabe über das Verhältnis der entsprechenden Werte zurück.

System_CAPS_pubmethodEquals(Object)

Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.(Überschreibt ValueType.Equals(Object).)

System_CAPS_protmethodFinalize()

Gibt einem Objekt Gelegenheit, Ressourcen freizugeben und andere Bereinigungen durchzuführen, bevor es von der Garbage Collection freigegeben wird. (Geerbt von „Object“.)

System_CAPS_pubmethodSystem_CAPS_staticFormat(Type, Object, String)

Konvertiert den angegebenen Wert eines angegebenen Enumerationstyps unter Berücksichtigung des angegebenen Formats in die entsprechende Zeichenfolgendarstellung.

System_CAPS_pubmethodGetHashCode()

Gibt den Hashcode für den Wert dieser Instanz zurück.(Überschreibt ValueType.GetHashCode().)

System_CAPS_pubmethodSystem_CAPS_staticGetName(Type, Object)

Ruft den Namen der Konstanten in der angegebenen Enumeration mit dem angegebenen Wert ab.

System_CAPS_pubmethodSystem_CAPS_staticGetNames(Type)

Ruft ein Array mit den Namen der Konstanten in einer angegebenen Enumeration ab.

System_CAPS_pubmethodGetType()

Ruft den Type der aktuellen Instanz ab.(Geerbt von „Object“.)

System_CAPS_pubmethodGetTypeCode()

Gibt den Typcode des zugrunde liegenden Typs dieses Enumerationsmembers zurück.

System_CAPS_pubmethodSystem_CAPS_staticGetUnderlyingType(Type)

Gibt den zugrunde liegenden Typ der angegebenen Enumeration zurück.

System_CAPS_pubmethodSystem_CAPS_staticGetValues(Type)

Ruft ein Array mit den Werten der Konstanten in einer angegebenen Enumeration ab.

System_CAPS_pubmethodHasFlag(Enum)

Bestimmt, ob ein oder mehrere Bitfelder in der aktuellen Instanz festgelegt werden.

System_CAPS_pubmethodSystem_CAPS_staticIsDefined(Type, Object)

Gibt eine Angabe darüber zurück, ob eine angegebene Enumeration eine Konstante mit einem angegebenen Wert enthält.

System_CAPS_protmethodMemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.(Geerbt von „Object“.)

System_CAPS_pubmethodSystem_CAPS_staticParse(Type, String)

Konvertiert die Zeichenfolgendarstellung des Namens oder des numerischen Werts einer oder mehrerer Enumerationskonstanten in ein entsprechendes Enumerationsobjekt.

System_CAPS_pubmethodSystem_CAPS_staticParse(Type, String, Boolean)

Konvertiert die Zeichenfolgendarstellung des Namens oder des numerischen Werts einer oder mehrerer Enumerationskonstanten in ein entsprechendes Enumerationsobjekt. Ein Parameter gibt an, ob beim Vorgang die Groß-/Kleinschreibung nicht beachtet wird.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, Byte)

Konvertiert die angegebene 8-Bit-Ganzzahl ohne Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, Int16)

Konvertiert die angegebene 16-Bit-Ganzzahl mit Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, Int32)

Konvertiert die angegebene 32-Bit-Ganzzahl mit Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, Int64)

Konvertiert die angegebene 64-Bit-Ganzzahl mit Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, Object)

Konvertiert das angegebene Objekt mit einem ganzzahligen Wert in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, SByte)

Konvertiert den angegebenen Wert einer 8-Bit-Ganzzahl mit Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, UInt16)

Konvertiert den angegebenen Wert einer 16-Bit-Ganzzahl ohne Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, UInt32)

Konvertiert den angegebenen Wert einer 32-Bit-Ganzzahl ohne Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodSystem_CAPS_staticToObject(Type, UInt64)

Konvertiert den angegebenen Wert einer 64-Bit-Ganzzahl ohne Vorzeichen in einen Enumerationsmember.

System_CAPS_pubmethodToString()

Konvertiert den Wert dieser Instanz in die entsprechende Zeichenfolgendarstellung.(Überschreibt ValueType.ToString().)

System_CAPS_pubmethodToString(IFormatProvider)

Veraltet.Diese Methodenüberladung ist veraltet. Verwenden Sie Enum.ToString().

System_CAPS_pubmethodToString(String)

Konvertiert den Wert dieser Instanz anhand des angegebenen Formats in die entsprechende Zeichenfolgendarstellung.

System_CAPS_pubmethodToString(String, IFormatProvider)

Veraltet.Diese Methodenüberladung ist veraltet. Verwenden Sie Enum.ToString(String).

System_CAPS_pubmethodSystem_CAPS_staticTryParse(Of TEnum)(String, TEnum)

Konvertiert die Zeichenfolgendarstellung des Namens oder des numerischen Werts einer oder mehrerer Enumerationskonstanten in ein entsprechendes Enumerationsobjekt. Der Rückgabewert gibt an, ob die Konvertierung erfolgreich abgeschlossen wurde.

System_CAPS_pubmethodSystem_CAPS_staticTryParse(Of TEnum)(String, Boolean, TEnum)

Konvertiert die Zeichenfolgendarstellung des Namens oder des numerischen Werts einer oder mehrerer Enumerationskonstanten in ein entsprechendes Enumerationsobjekt. Ein Parameter gibt an, ob beim Vorgang die Groß-/Kleinschreibung beachtet wird. Der Rückgabewert gibt an, ob die Konvertierung erfolgreich abgeschlossen wurde.

NameBeschreibung
System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToBoolean(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in einen booleschen Wert.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToByte(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 8-Bit-Ganzzahl ohne Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToChar(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in ein Unicode-Zeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDateTime(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine DateTime.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDecimal(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine Decimal.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToDouble(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine Gleitkommazahl mit doppelter Genauigkeit.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt16(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 16-Bit-Ganzzahl mit Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt32(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 32-Bit-Ganzzahl mit Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToInt64(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 64-Bit-Ganzzahl mit Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSByte(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 8-Bit-Ganzzahl mit Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToSingle(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine Gleitkommazahl mit einfacher Genauigkeit.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToType(Type, IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in einen angegebenen Typ.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt16(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 16-Bit-Ganzzahl ohne Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt32(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 32-Bit-Ganzzahl ohne Vorzeichen.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIConvertible.ToUInt64(IFormatProvider)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Konvertiert den aktuellen Wert auf Grundlage des zugrunde liegenden Typs in eine 64-Bit-Ganzzahl ohne Vorzeichen.

An enumeration is a set of named constants whose underlying type is any integral type. If no underlying type is explicitly declared, T:System.Int32 is used. T:System.Enum is the base class for all enumerations in the .NET Framework. Enumeration types are defined by the enum keyword in C# and the Enum...End Enum construct in Visual Basic.

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. For more information, see the Non-Exclusive Members and the Flags Attribute section and the T:System.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
Non-exclusive members and the Flags attribute
Adding enumeration methods

Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values. The following example illustrates the syntax used by C# and Visual Basic to define an enumeration. It creates an enumeration named ArrivalStatus that has three members: ArrivalStatus.Early, ArrivalStatus.OnTime, and ArrivalStatus.Late. Note that in both cases, the enumeration does not explicitly inherit from T:System.Enum; the inheritance relationship is handled implicitly by the compiler.

Public Enum ArrivalStatus As Integer
   Late = -1
   OnTime = 0
   Early = 1
End Enum
System_CAPS_warningWarnung

You should never create an enumeration type whose underlying type is non-integral or T:System.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.

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. The following example instantiates an ArrivalStatus whose value is ArrivalStatus.OnTime.

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:

  • 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. The following example creates an ArrivalStatus object whose value is ArrivalStatus.Early in this way.

    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 default constructor. 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.

    Dim status1 As New ArrivalStatus()
    Console.WriteLine("Arrival Status: {0} ({0:D})", status1)
    ' The example displays the following output:
    '        Arrival Status: OnTime (0)
    
  • By calling the M:System.Enum.Parse(System.Type,System.String) or M:System.Enum.TryParse``1(System.String,``0@) method to parse a string that contains the name of a constant in the enumeration. For more information, see the Parsing Enumeration Values section.

  • By calling the M:System.Enum.ToObject(System.Type,System.Byte) method to convert an integral value to an enumeration type. For more information, see the Performing Conversions section.

We recommend that you use the following best practices when you define enumeration types:

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

You cannot define new methods when you are creating an enumeration. However, an enumeration type inherits a complete set of static and instance methods from the T:System.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.

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.

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

Dim value4 As Integer = CInt(status3)

The T:System.Enum class also includes a M:System.Enum.ToObject(System.Type,System.Byte) method that converts a value of any integral type to an enumeration value. The following example uses the M:System.Enum.ToObject(System.Type,System.Int32) method to convert an T:System.Int32 to an ArrivalStatus value. Note that, because the M:System.Enum.ToObject(System.Type,System.Byte) returns a value of type T:System.Object, the use of a casting or conversion operator may still be necessary to cast the object to the enumeration type.

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. To prevent this, you can pass the integer to the M:System.Enum.IsDefined(System.Type,System.Object) method before performing the conversion. The following example uses this method to determine whether the elements in an array of integer values can be converted to ArrivalStatus values.

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

Although the T:System.Enum class provides explicit interface implementations of the T:System.IConvertible interface for converting from an enumeration value to an integral type, you should use the methods of the T:System.Convert class, such as M:System.Convert.ToInt32(System.Object), to perform these conversions. The following example illustrates how you can use the M:System.Enum.GetUnderlyingType(System.Type) method along with the M:System.Convert.ChangeType(System.Object,System.Type) 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.

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

The M:System.Enum.Parse(System.Type,System.String) and M:System.Enum.TryParse``1(System.String,``0@) 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. To prevent this, the M:System.Enum.IsDefined(System.Type,System.Object) 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 M:System.Enum.Parse(System.Type,System.String) and M:System.Enum.TryParse``1(System.String,``0@) methods. 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.

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

You can convert enumeration values to their string representations by calling the static M:System.Enum.Format(System.Type,System.Object,System.String) method, as well as the overloads of the instance M:System.Enum.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. 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.

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

The T:System.Enum type does not implement the T:System.Collections.IEnumerable or T:System.Collections.Generic.IEnumerable`1 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.

  • You can call the M:System.Enum.GetNames(System.Type) method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the M:System.Enum.Parse(System.Type,System.String) method to convert the string to its equivalent enumeration value. The following example illustrates this approach.

    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)      
    
  • You can call the M:System.Enum.GetValues(System.Type) method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the M:System.Enum.ToObject(System.Type,System.Int32) method to convert the integer to its equivalent enumeration value. The following example illustrates this approach.

    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)
    

One common use of an enumeration is to represent a set of mutually exclusive values. For example, an ArrivalStatus instance can have a value of Early, OnTime, or Late. 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. The T:System.FlagsAttribute attribute can be used to indicate that the enumeration consists of bit fields. 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 As Integer
   None = 0
   Dog = 1
   Cat = 2
   Bird = 4
   Rodent = 8
   Reptile = 16
   Other = 32
End Enum

The Pets enumeration can then be used as shown in the following example.

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)      

The following best practices should be used when defining a bitwise enumeration and applying the T:System.FlagsAttribute attribute.

  • Use the T:System.FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

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

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

  • A convenient way to test whether a flag is set in a numeric value is to call the instance M:System.Enum.HasFlag(System.Enum) method, as shown in the following example.

    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.

    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.      
    
  • Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. 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.

    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.

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 T:System.Enum class. However, you can use extension methods to add functionality to a particular enumeration type.

In the following example, the Grades enumeration represents the possible letter grades that a student may receive in a class. 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. The Extensions class also contains a static read-write variable that defines the minimum passing grade. The return value of the Passing extension method reflects the current value of that variable.

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.

The following example demonstrates using an enumeration to represent named values and another enumeration to represent named bit fields.

Public Class EnumTest
    Enum Days
        Saturday
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
    End Enum 

    Enum BoilingPoints
        Celsius = 100
        Fahrenheit = 212
    End Enum 

    <FlagsAttribute()> _
    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 

Universelle Windows-Plattform
Verfügbar seit 8
.NET Framework
Verfügbar seit 1.1
Portierbare Klassenbibliothek
Unterstützt in: portierbare .NET-Plattformen
Silverlight
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
Windows Phone
Verfügbar seit 8.1

This type is thread safe.

Zurück zum Anfang
Anzeigen: