天天看点

把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,如需转载请自行联系原作者

继续阅读