BloggerAds廣告

2015年5月6日 星期三

[C#]Enum與其他型別相互轉換

Enum convert with the other type


這對於將參數變成可讀的String很有幫助

參考網址1
  
public enum EnumDays: byte {
    Sun = 1,
    Mon = 2,
    // ...
}

//then you will able to do it:

EnumDays day = EnumDays.Mon;
byte byteDay = (byte)day;
EnumDays tempDay = (EnumDays)byteDay;

參考網址2

  
using System;
 
public class CSharpLab
{
    public enum State
    {
        Init, Open, Proc, Close, Done = 9
    }
    public static void Test()
    {
        State st = State.Init;
        //列出所有名稱
        foreach (string en in Enum.GetNames(typeof(State)))
            Console.WriteLine("Enum Name: " + en);
        //列舉背後有值, 預設由零開始排, 但也可自訂
        //TIPS: typeof(State)與st.GetType()都可取得列舉型別
        foreach (int v in Enum.GetValues(st.GetType()))
            Console.WriteLine("Enum Value: " + v.ToString());
        //將列舉轉為字串
        Console.WriteLine("Enum To String: " + st.ToString());
        //將字串轉為列舉
        st = (State)Enum.Parse(typeof(State), "proc", true);
        Console.WriteLine("String To Enum: " + st);
        try {
            Console.WriteLine("String To Enum(not found): " + 
                                    Enum.Parse(typeof(State), "WTF"));
        } catch (Exception ex) {
            Console.WriteLine("Error when Enum.Parse: " + ex.Message);
        }
        //將列舉轉為數字
        Console.WriteLine("Enum to Int: " + st + " " + (int)st);
        //將數字轉回列舉
        st = (State)9;
        Console.WriteLine("Int to Enum: " + st);
        //小心數字轉換對不上時不會有錯誤,但會出現非列舉值
        st = (State)100;
        Console.WriteLine("Int(100) to Enum: " + st);
        //如果數字有連續,可以用+1, -1找上一個下一個
        //注意: 以下範例並未檢查邊界及數值不連續的狀況, 
        //並非嚴謹寫法,僅為簡單示意,勿用於正式用途
        st = State.Proc;
        State next = (State)((int)st)+1;
        State prev = (State)((int)st)-1;
        Console.WriteLine("Now = " + st + " Next = " + next + " Prev = " + prev);
    }
}