码迷,mamicode.com
首页 > Windows程序 > 详细

C#枚举

时间:2020-04-20 16:11:47      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:ref   mem   typeof   des   特性   each   iss   返回   ring   

C#获取枚举描述

首先创建如下枚举信息,并使用DescriptionAttribute类增加描述特性。

/// <summary>
/// 状态编码枚举
/// </summary>
public enum StatusCode
{
    /// <summary>
    /// 操作成功
    /// </summary>
    [Description("操作成功")]
    Success = 200,
 
    /// <summary>
    /// 参数缺失
    /// </summary>
    [Description("参数缺失")]
    MissingParam = 201,
 
    /// <summary>
    /// 操作失败
    /// </summary>
    [Description("操作失败")]
    Failure = 202
}
方法一:编写获取枚举描述方法
/// <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#枚举

标签:ref   mem   typeof   des   特性   each   iss   返回   ring   

原文地址:https://www.cnblogs.com/newcapecjmc/p/12737901.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!