C#获取枚举Enum的描述

简单封装个扩展方法,方便下次使用。

using System.ComponentModel;

namespace Order.Core.API.Enums
{
    public enum AccountStatus
    {
        [Description("账号不存在!")]
        AccountNotExist = 1,
        [Description("密码错误!")]
        PasswordError = 2,
        [Description("账号验证成功!")]
        Success = 4

    }
}

using System;
using System.ComponentModel;
using System.Reflection;

namespace Order.Core.API.Extensions
{
    public static class EnumExtensions
    {
        public static string GetDescription(this Enum value) 
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
            return attribute == null ? value.ToString() : attribute.Description;
        }
    }
}

你可能感兴趣的:(c#)