日期:2014-05-17  浏览次数:20546 次

【分享贴】将string转换成枚举的通用方法
小弟愚钝,不怎么会写代码,以前遇到要将string转化成枚举的时候,都是去遍历枚举进行字符串匹配来取得枚举,用的比较多的情况如:default.aspx?type=black,要在程序里通过以下方法取得black:

enum Color
{
  red,
  white,
  black,
  yellow
}

Color GetColorType(string s)
{
  Color color = Color.red;
  foreach(Color c in Enum.GetValues(typeof(Color)))
  {
  if(s == c)
  {
  color = c;
  break;
  }
  }
}

所以,针对这种情况就必须遇到不同的枚举,就得写不同的foreach来实现此功能,甚是麻烦。

后来,动用了几十亿个细胞(小弟真是不才),才想了以下这一招通用函数来转换:


C# code

        public static object EnumParse(Type type, object value, object defaultValue)
        {
            object obj = null;
            try
            {
                obj = Enum.Parse(type, value.ToString());
            }
            catch
            {
                return defaultValue;
            }

            if (obj.ToString() == "0" || ConvertToInt(obj.ToString()) != 0)
                return defaultValue;
            else
                return obj;
        }
        public static int ConvertToInt(string s)
        {
            try
            {
                return Convert.ToInt16(s);
            }
            catch
            {
                return 0;
            }
        }




最终,最上面的foreach代码可简化为:

Color color = (Color)EnumParse(typeof(Color),Request.QueryString["type"],Color.red);


OK,就这样,没别的意思,分享、献丑一下而已,顺便散点小分。

------解决方案--------------------
感谢分享
------解决方案--------------------
感谢分享····
------解决方案--------------------
用扩展方法优化了一下
C# code

        /// <summary>
        /// 根据字符串返回对应枚举类型
        /// </summary>
        /// <typeparam name="T">对应枚举类型</typeparam>
        /// <param name="source">字符串</param>
        /// <returns></returns>
        public static T GetEnumByValue<T>(this string source)
        {
            if (typeof(T).BaseType == typeof(Enum))
            {
                foreach (T value in Enum.GetValues(typeof(T)))
                {
                    if (source == value.ToString())
                    {
                        return value;
                    }
                }
            }
            else
            {
                throw new ArgumentException("T必须为枚举类型");
            }

            return default(T);
        }
//调用
 public enum Color
    {
        black,
        red,
        blue
    }
    Color obj = "blue".GetEnumByValue<Color>();

------解决方案--------------------
C# code

    public object GetValue(Type type, string value, object defaultValue)
    {
        FieldInfo f = type.GetField(value, BindingFlags.Static | BindingFlags.Public);
        if (f == null)
            return defaultValue;
        else
        {
            Color c = 0;
            return f.GetValue(c);
        } 
    }

Color c = (Color)GetValue(typeof(Color), "black", Color.red);

------解决方案--------------------
C# code
    protected void Page_Load(object sender, EventArgs e)
    {
        Color c = (Color)GetValue(typeof(Color), "white", Color.red);
        Response.Write(c);
    }
    public object GetValue(Type type, string value, object defaultValue)
    {
        FieldInfo f = type.GetField(value, BindingFlags.Static | BindingFlags.Public);
        if (f == null)
            return defaultValue;