Enum 结构

引用自: http://technet.microsoft.com/zh-cn/office/system.enum(VS.85).aspx
为枚举提供基类。

命名空间: System
程序集: mscorlib(在 mscorlib.dll 中)

Visual Basic(声明)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public MustInherit Class Enum
    Inherits ValueType
    Implements IComparable, IFormattable, IConvertible
Visual Basic (用法)
Dim instance As Enum
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class Enum abstract : public ValueType, IComparable, IFormattable, IConvertible
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public abstract class Enum extends ValueType implements IComparable, IFormattable, 
    IConvertible
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public abstract class Enum extends ValueType implements IComparable, IFormattable, 
    IConvertible
XAML
不适用。

枚举是一个指定的常数,其基础类型可以是除 Char 外的任何整型。如果没有显式声明基础类型,则使用 Int32。编程语言通常提供语法来声明由一组已命名的常数和它们的值组成的枚举。

Enum 提供比较此类的实例的方法、将实例的值转换为其字符串表示形式的方法、将数字的字符串表示形式转换为此类的实例的方法和创建指定枚举和值的实例的方法。

也可以将枚举视为位域。有关更多信息,请参见 FlagsAttribute。

实现的接口

此类从 ValueType 继承,并实现 IComparable、IFormattable 和 IConvertible 接口。使用 Convert 类来进行转换,而不使用此类的 IConvertible 的显式接口成员实现。

用于 FlagsAttribute 和 Enum 的准则

  • 只有要对数值执行按位运算(AND、OR、XOR)时才对枚举使用 FlagsAttribute 自定义属性。

  • 用 2 的幂(即 1、2、4、8 等)定义枚举常量。这意味着组合的枚举常量中的各个标志都不重叠。

  • 请考虑为常用标志组合创建一个枚举常量。例如,如果有一个用于文件 I/O 操作的枚举包含枚举常量 Read = 1 和 Write = 2,请考虑创建枚举常量 ReadWrite = Read OR Write,该枚举常量将 Read 和 Write 标志组合在一起。此外,在某些情况下,可能会将用于组合标志的按位 OR 运算视为一种高级概念,在简单任务中不需要执行此操作。

  • 将负数定义为标志枚举常量时应谨慎,因为很多标志位置都可能设置为 1,这可能使您的代码产生混淆并易于发生代码错误。

  • 测试数值中是否已设置标志的一种简便方法为:在数值和标志枚举常量之间执行按位“与”操作,这种方法会将数值中与标志不对应的所有位都设置为零,然后测试该操作的结果是否等于该标志枚举常量。

  • 将 None 用作值为零的标志枚举常量的名称。在按位 AND 运算中,不能使用 None 枚举常量测试标志,因为所得的结果始终为零。但是,您可以在数值与 None 枚举常量之间执行逻辑(不是按位)比较,以确定数值中是否已设置任何位。

    如果创建的是值枚举而不是标志枚举,创建 None 枚举常量仍十分有用。原因是在默认情况下,公共语言运行库会将用于枚举的内存初始化为零。因此,如果不定义值为零的常量,则枚举在创建时将包含非法值。

    如果明显存在应用程序需要表示的默认情况,请考虑使用值为零的枚举常量表示默认值。如果不存在默认情况,请考虑使用值为零的枚举常量(这意味着该情况不由任何其他枚举常量表示)。

  • 不要定义只映射枚举本身状态的枚举值。例如,不要定义只标记枚举末尾的枚举常量。如果需要确定枚举的最后一个值,请显式检查该值。此外,如果枚举常量范围中的所有值都有效,还可以对第一个和最后一个枚举常量执行范围检查。

  • 不要指定保留供以后使用的枚举常量。

  • 在定义采用枚举常量作为值的方法或属性时,应考虑对该值进行验证。原因是即使数值未在枚举中定义,也可以将数值强制转换为枚举类型。

下面的代码示例演示使用一个枚举表示指定的值,并使用另一个枚举表示指定的位域。

Visual Basic
复制代码
Imports System

Public Class EnumTest
    
    Enum Days
        Saturday
        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
    End Enum 'Days
    
    Enum BoilingPoints
        Celcius = 100
        Fahrenheit = 212
    End Enum 'BoilingPoints
    
    <FlagsAttribute()> _
    Enum Colors
        Red = 1
        Green = 2
        Blue = 4
        Yellow = 8
    End Enum 'Colors

    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 'Main
End Class 'EnumTest
C#
复制代码
using System;

public class EnumTest {
    enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
    enum BoilingPoints { Celcius = 100, Fahrenheit = 212 };
    [FlagsAttribute]
    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);
    }
}
C++
复制代码
using namespace System;
enum class Days
{
   Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday
};

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

[FlagsAttribute]

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 ) );
}
J#
复制代码
import System.*;

public class EnumTest
{
    enum Days
    {
        saturday (0),
        sunday (1),
        monday (2),
        tuesday (3),
        wednesday (4),
        thursday (5),
        friday (6);
    } //Days

    enum BoilingPoints
    {
        celsius (100),
        fahrenheit (212);
    } //BoilingPoints

    /** @attribute FlagsAttribute()
     */
    enum Colors
    {
        red (1),
        green (2),
        blue (4),
        yellow (8);
    } //Colors

    public static void main(String[] args)
    {
        Type weekdays = Days.class.ToType();
        Type boiling = BoilingPoints.class.ToType();

        Console.WriteLine("The days of the week, and their corresponding"
            + " values in the Days Enum are:");
        String s[] = Enum.GetNames(weekdays);
        for (int iCtr = 0; iCtr < s.length; iCtr++) {
            Console.WriteLine("{0,-11}= {1}", s[iCtr],
                Enum.Format(weekdays, Enum.Parse(weekdays, s[iCtr]), "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:");
        String s1[] = Enum.GetNames(boiling);
        for (int iCtr = 0; iCtr < s1.length; iCtr++) {
            Console.WriteLine("{0,-11}= {1}", s1[iCtr], 
                Enum.Format(boiling, Enum.Parse(boiling, s1[iCtr]), "d"));
        }
        Colors myColors = Colors.red | Colors.blue | Colors.yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}",
            myColors);
    } //main
} //EnumTest
JScript
复制代码
import System;

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

    public static function Main() {

        var weekdays : Type = Days;
        var boiling : Type = BoilingPoints;

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

        for( var i : int in Enum.GetNames(weekdays) )
            Console.WriteLine( "{0,-11}= {1}", Enum.GetNames(weekdays).GetValue(i), 
            Enum.Format( weekdays, Enum.Parse(weekdays, Enum.GetNames(weekdays).GetValue(i)), "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:");

        for ( var j : int in Enum.GetNames(boiling) )
            Console.WriteLine( "{0,-11}= {1}", Enum.GetNames(boiling).GetValue(j), 
            Enum.Format(boiling, Enum.Parse(boiling, Enum.GetNames(boiling).GetValue(j)), "d"));

        var myColors : Colors = Colors.Red | Colors.Blue | Colors.Yellow;
        Console.WriteLine();
        Console.WriteLine("myColors holds a combination of colors. Namely: {0}", myColors);
    }
}

你可能感兴趣的:(Enum 结构)