欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#获取枚举的描述

程序员文章站 2022-06-12 17:06:02
...
 public enum Demos
    {
        PreValidation = 10,
        PreOperation = 20,
        PostOperation = 40
    }

   var dsa=Enum.GetName(typeof(Demos),40); //40为枚举的值
    Console.WriteLine(dsa);                //打印出来则是枚举的描述
 /// <summary>
    /// 状态编码枚举
    /// </summary>
    public enum StatusCode
    {
        /// <summary>
        /// 操作成功
        /// </summary>
        [Description("操作成功")]
        Success = 2000,

        /// <summary>
        /// 参数缺失
        /// </summary>
        [Description("参数缺失")]
        MissingParam = 3000,

        /// <summary>
        /// 操作失败
        /// </summary>
        [Description("操作失败")]
        Failure = 4000
    }


            Type type = StatusCode.Success.GetType();
            FieldInfo fd = type.GetField(StatusCode.Success.ToString());
            if (fd == null) return;

            object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
            foreach (DescriptionAttribute attr in attrs)
            {
                Console.WriteLine(attr.Description);
            }
相关标签: c# 枚举类