参考:https://www.cnblogs.com/jonney-wang/p/6732875.html
思路:通过反射获取枚举类的Field,再用 Field 获取 DescriptionAttribute 属性。反之亦然
// 枚举
public enum enumStudent
{
[Description("性别")]
sex = 0,
[Description("年龄")]
age = 1,
}
// 获取方法
public string GetDescriptionByEnum(Enum enumValue)
{
string value = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length == 0) //当描述属性没有时,直接返回名称
return value;
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
// 调用示例
GetDescriptionByEnum(enumStudent.age) → 年龄
public T GetEnumByDescription<T>(string description) where T : Enum
{
System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
foreach(System.Reflection.FieldInfo field in fields)
{
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
{
return (T)field.GetValue(null);
}
}
throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
}
// 调用示例
GetEnumByDescription<enumStudent>("性别").ToString() → sex