C#获取枚举描述
程序员文章站
2022-06-12 17:06:56
...
首先创建如下枚举信息,并使用DescriptionAttribute类增加描述特性。
/// <summary>
/// 状态编码枚举
/// </summary>
public enum StatusCode
{
/// <summary>
/// 操作成功
/// </summary>
[Description("操作成功")]
Success = 2000,
/// <summary>
/// 参数缺失
/// </summary>
[Description("参数缺失")]
MissingParam = 3000,
/// <summary>
/// 操作失败
/// </summary>
[Description("操作失败")]
Failure = 4000
}
方法一:编写获取枚举描述方法
/// <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();
}
调用方式:
string description = GetDescription(StatusCode.Success);
方法二:通过枚举扩展类
using System;
using System.ComponentModel;
using System.Reflection;
/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
/// <summary>
/// 获取枚举的描述信息
/// </summary>
public static string GetDescription(this Enum em)
{
Type type = em.GetType();
FieldInfo fd = type.GetField(em.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
string name = string.Empty;
foreach (DescriptionAttribute attr in attrs)
{
name = attr.Description;
}
return name;
}
}
调用方式:
string description = StatusCode.Success.GetDescription();
上一篇: C# 获取Json中的List
下一篇: C# 读取Json文件