枚举技巧~为枚举加Describe属性,输出枚举元素的说明信息

简介:

这是枚举公用属性类:

#region 枚举属性扩展类

    /// <summary>

    /// 枚举扩展方法

    /// </summary>

    public static class EnumExtensions

    {

        public static string GetDescription(this Enum obj)

        {

            return GetDescription(obj, false);

        }

        public static string GetDescription(this Enum obj, bool isTop)

        {

            if (obj == null)

            {

                return string.Empty;

            }

            try

            {

                Type _enumType = obj.GetType();

                DescriptionAttribute dna = null;

                if (isTop)

                {

                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute));

                }

                else

                {

                    FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));

 

                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(

 

                       fi, typeof(DescriptionAttribute));

                }

                if (dna != null && string.IsNullOrEmpty(dna.Description) == false)

                    return dna.Description;

            }

            catch

            {

                throw;

            }

            return obj.ToString();

 

        }

 

    }

    #endregion

一个普通的枚举

 public enum OpreateType

    {

        [Description("添加")]

        Add = 0,

        Del = 1,

        Update = 2,

        Import = 3,

    }

输出它指定枚举元素的描述信息

  Console.WriteLine(OpreateType.Add.GetDescription());

 本文转自博客园张占岭(仓储大叔)的博客,原文链接:枚举技巧~为枚举加Describe属性,输出枚举元素的说明信息,如需转载请自行联系原博主。

目录
相关文章
|
29天前
|
安全 算法 编译器
【C++基础语法 枚举】C/C++ 中enum枚举量的介绍:介绍enum枚举量在C/C中的作用和使用方法
【C++基础语法 枚举】C/C++ 中enum枚举量的介绍:介绍enum枚举量在C/C中的作用和使用方法
31 2
判断Object中数据类型(已知类型、未知类型))
判断Object中数据类型(已知类型、未知类型))
108 0
lodash创建自身可枚举属性的值为数组
lodash创建自身可枚举属性的值为数组
64 0
|
前端开发 Java
Java 获取Enum枚举中的值,以列表方式返回
Java 获取Enum枚举中的值,以列表方式返回
1751 0
|
开发者
枚举(枚举中定义其它结构)|学习笔记
快速学习 枚举(枚举中定义其它结构)
|
Python
变量的赋值定义分类和类型判断
几乎在所有编程语言当中变量是最先接触语法概念,那么什么是变量,变量应该怎么定义呢,定义变量又该注意哪些因素呢?这里我们来给大家详细聊聊。
变量的赋值定义分类和类型判断