C#中获取枚举值的介绍
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;
}
举例有枚举类型ETypeResult
:
public enum ETypeResult
{
[Description("成功")]
Success= -1,
[Description("未知")]
UnKnow= 0,
[Description("失败")]
Fail= 1,
}
调用:
GetEnumDescription(ETypeResult.Success)
// 返回"成功"