天天看點

把Enum與Int32、String的互相轉換的代碼

平時我們須要把Enum類型與int(或者string)類型進行互相轉換,利用下面的泛型程式設計,可以處理所有情況了。

public static class EnumHelper2<T> 

    public static String Enum2String(T value) 

    { 

        return value.ToString(); 

    } 

    public static T String2Enum(string value, bool ignoreCase) 

        return (T)Enum.Parse(typeof(T), value, ignoreCase); 

    public static int Enum2Int(T value) 

        return Convert.ToInt32(value); 

    public static T Int2Enum(int value) 

        if (Enum.IsDefined(typeof(T), value)) 

            return (T)Enum.ToObject(typeof(T), value); 

        else 

            throw new Exception(value + " is not defined"); 

public static class EnumHelper 

    public static int ToInt32<T>(T value) 

    public static T FromInt32<T>(int value) 

        return (T)Enum.ToObject(typeof(T), value); 

    public static T Parse<T>(string value, bool ignoreCase) 

            return (T)Enum.Parse(typeof(T), value, ignoreCase); 

    public static T Parse<T>(int value) 

本文轉自 h2appy  51CTO部落格,原文連結:http://blog.51cto.com/h2appy/412021,如需轉載請自行聯系原作者

繼續閱讀