【分享贴】将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; else { return f.GetValue(null); } }
[解决办法]
[解决办法]
感谢分享。
[解决办法]
通用字符串转枚举,可指定是否区分大小写
- C# code
public static TEnum ToEnum<TEnum>(this string input, bool ingoreCase) where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new InvalidCastException("TEnum 不是枚举类型。"); } return (TEnum)Enum.Parse(typeof(TEnum), input, ingoreCase); }
[解决办法]
感谢分享
[解决办法]
感谢分享····
[解决办法]
感谢分享····
[解决办法]
感谢分享····
[解决办法]
不错不错
[解决办法]
支持!!感谢!
[解决办法]
顶起
[解决办法]
路过,喜欢看高手们的评论
[解决办法]
顶起
[解决办法]
为什么不用Enum.TryParse,这个还是泛型方法,
如果是.net3.5或以上,可以为String类型写个扩展方法,如下
- C# code
class EnumTest { public static void Test() { Console.WriteLine("black".Parse<Color>(Color.Red)); } } public enum Color { [Description("红色")] Red, [Description("黑色")] Black, White } public static class EnumExtenstion { public static String GetDest<T>(this T value) { var field = typeof(T).GetField(value.ToString()); var attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), true); if (attrs.Length > 0) { return attrs[0].Description; } else { return "UNKNOWN"; } } public static T Parse<T>(this string value, T defaultValue) where T : struct { T v; if (!Enum.TryParse<T>(value, true, out v)) { v = defaultValue; } return v; } }
[解决办法]
不错不错