C# 获取枚举类型描述Description值

代码

/// 
        /// 获取当前枚举描述
        /// 
        /// 
        /// 
        public static string GetEnumDescription(this Enum enumValue)
        {
            try
            {
                Type type = enumValue.GetType();
                MemberInfo[] memInfo = type.GetMember(enumValue.ToString());
                if (null != memInfo && memInfo.Length > 0)
                {
                    object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (null != attrs && attrs.Length > 0)
                        return ((DescriptionAttribute)attrs[0]).Description;
                }
                return enumValue.ToString();
            }
            catch (Exception)
            {
                return "Unknown";
            }
        }

调用

class Program
    {
        static void Main(string[] args)
        {

            var Moel = new Model() { Name="张三",OrderBy=OrderType.News};
            var res = Moel.OrderBy.GetEnumDescription();

            Console.WriteLine(res);
            Console.ReadKey();
        }

    }
    public class Model
    {
        public string Name { get; set; }
        public OrderType OrderBy { get; set; }
    }
    /// 
    /// 排序类型,
    /// 
    public enum OrderType
    {
        /// 
        /// 最新排序
        /// 
        [Description("id desc")]
        News,
        /// 
        /// 热门排序
        /// 
        [Description("viewCount desc")]
        Hot,
    }

结果
C# 获取枚举类型描述Description值_第1张图片

你可能感兴趣的:(.NET,C#,C#获取枚举描述值)