C#实现获取枚举的描述
程序员文章站
2022-06-12 17:05:50
...
一个通用获取枚举的描述的方法
/// <summary>
/// 获取枚举的描述
/// </summary>
/// <param name="en">枚举</param>
/// <returns>返回枚举的描述</returns>
public static string GetDescription(Enum en)
{
Type type = en.GetType(); //获取类型
MemberInfo[] memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos!=null&&memberInfos.Length>0)
{
DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; //获取描述特性
if (attrs!=null&&attrs.Length>0)
{
return attrs[0].Description; //返回当前描述
}
}
return en.ToString();
}
示例:
/// <summary>
/// 上传状态
/// </summary>
public enum UploadState
{
[Description("上传失败")]
UploadFailed = -1,
[Description("正在上传")]
Uploading = 0,
[Description("上传成功")]
UploadSuccess = 1
}
调用代码:
EnumService.GetDescription(UploadState.UploadSuccess)
上一篇: 获取注册表键值并格式转换
下一篇: C#获取Json文件的树节点