C#获取枚举描述

首先创建如下枚举信息,并使用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();


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pan_junbiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值