【分享贴】将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来实现此功能,甚是麻烦。
后来,动用了几十亿个细胞(小弟真是不才),才想了以下这一招通用函数来转换:
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;
else
{
return f.GetValue(null);
}
}
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);
}
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;
}
}