没有优化,凑合着用吧。需要using System.ComponentModel;
/// <summary>
/// 根据属性描述获取枚举值
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="des">属性说明</param>
/// <returns>枚举值</returns>
public static T GetEnum<T>(string des) where T : struct, IConvertible
{
Type type = typeof(T);
if (!type.IsEnum)
{
return default(T);
}
T[] enums = (T[])Enum.GetValues(type);
T temp;
if (!Enum.TryParse(des, out temp))
{
temp = default(T);
}
for (int i = 0; i < enums.Length; i++)
{
string name = enums[i].ToString();
FieldInfo field = type.GetField(name);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
{
continue;
}
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
string edes = descriptionAttribute.Description;
if (des == edes)
{
temp = enums[i];
break;
}
}
return temp;
}
字符串转为枚举值:
//字符串转为枚举
public static T ToEnum<T>(this string enumName) where T : struct, IConvertible
{
Type type = typeof(T);
if (!type.IsEnum)
{
return default(T);
}
T temp;
if (!Enum.TryParse<T>(enumName, out temp))
{
temp = default(T);
}
return temp;
}
下面是获取枚举的属性描述的代码,来源于https://www.cnblogs.com/TanSea/p/6923743.html
//获取属性描述
public static string GetEnumDescription(Enum enumValue)
{
string value = enumValue.ToString();
FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs == null || objs.Length == 0) //当描述属性没有时,直接返回名称
{
return value;
}
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}