日期:2014-05-17 浏览次数:20585 次
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; } }
/// <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>();
------解决方案--------------------
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);
------解决方案--------------------
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;