在此例中,声明了一个枚举 Days。两个枚举数被显式转换为整数并赋给整型变量。


using System;
public class EnumTest
{
    enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

    static void Main()
    {
     int x = (int)Days.Sun;int
  y = (int)Days.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}

输出

 
Sun = 2
            Fri = 7


在此例中,使用了基类选项来声明成员类型是 long 的 enum

using System;
public class EnumTest
{
    enum Range :long {Max = 2147483648L, Min = 255L};
    static void Main()
    {
        long x = (long)Range.Max;     
        long y = (long)Range.Min;
        Console.WriteLine("Max = {0}", x);
        Console.WriteLine("Min = {0}", y);
    }
}

输出

 
Max = 2147483648
            Min = 255

下面的代码示例阐释 enum 声明上的 System.FlagsAttribute 属性的使用和效果。
using System;

[Flags]
public enum CarOptions
{
    SunRoof = 0x01,
    Spoiler = 0x02,
    FogLights = 0x04,
    TintedWindows = 0x08,
}

class FlagTest
{
    static void Main()
    {
        CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
        Console.WriteLine(options);
        Console.WriteLine((int)options);
    }
}

输出

 
SunRoof, FogLights
            5


请注意,如果移除 FlagsAttribute,此示例的输出为:

5

5

posted on 2007-08-06 12:09  萧佰刚  阅读(470)  评论(0编辑  收藏  举报