C#:列舉

Rain Man發表於2014-04-08

1. 列舉的綜合運用

public enum Color { yellow, blue, green }

class Program
{
    static void Main(string[] args)
    {
        // 1. 正常使用列舉元素
        Console.WriteLine(Color.yellow);    // 輸出: yellow

        // 2. 通過定義變數使用列舉元素
        Color c1 = Color.blue;
        Console.WriteLine(c1);             // 輸出: blue

        // 3. 列舉的元素實際上是“Int”,而且依次編號(增量為1)
        Console.WriteLine(Convert.ToInt32(Color.green));    // 輸出2

        // 4. Enum.Parse()方法,根據“字串”獲取對應的列舉元素
        Color c2 = (Color)Enum.Parse(typeof(Color), "yellow", true);
        if (c2 == Color.yellow)
        {
            Console.WriteLine("Yes");   // 輸出: Yes
        }

        // 5. 根據“下標”獲取對應的字串
        string c3 = Enum.GetName(typeof(Color), 1);
        Console.WriteLine(c3);            // 輸出: blue

        // 6. 依次輸出列舉元素(下標)
        foreach(int i in Enum.GetValues(typeof(Color)))
        {
            Console.WriteLine(i.ToString());                    // 依次輸出: 1, 2, 3
            Console.WriteLine(Enum.GetName(typeof(Color), i));  // 根據“下標”獲取對應字串,依次輸出: yellow, blue, green
        }

        // 7.依次輸出列舉值對應的字串
        foreach (string c in Enum.GetNames(typeof(Color)))
        {
            Console.WriteLine(c);      // 依次輸出: yellow, blue, green
        }
    }
}

2. 列舉的值

  • 列舉元素不是變數,而是常數。因為是常量,所以不能對列舉元素進行賦值。
  • 列舉元素作為常量,它們是有值的,值依次遞增,增量為1。
public enum Color { yellow, blue, green }
等同於:
public enum Color { yellow = 0, blue = 1, green = 2 }
public enum Color { yellow, blue = 100, green }
等同於:
public enum Color { yellow, blue = 100, green = 101 }

3. Enum.Parse(enumType, value, ignoreCase)

根據給定“字串”獲取列舉的值,返回object(使用時需要強型別轉換)。

// enumType: 列舉的 Type
// value: 包含要轉換的值或名稱的字串
// ignoreCase: 如果為 true,則忽略大小寫;否則考慮大小寫
// 返回值: enumType 型別的物件,其值由 value 表示
public static Object Parse (
    Type enumType,
    string value,
    bool ignoreCase
)

相關文章