将不确定变为确定~Flag特性的枚举是否可以得到Description信息

简介:

之前我写过对于普通枚举类型对象,输出Description特性信息的方法,今天主要来说一下,如何实现位域Flags枚举元素的Description信息的方法。

对于一个普通枚举对象,它输出描述信息是这样的

   public enum Status
    {
        [Description("正常")]
        Normal = -1,
        [Description("删除")]
        Deletet = 0,
        [Description("冻结")]
        Freezed = 1,
    }
   Status status = Status.Normal;
   Console.WriteLine(status.GetDescription());

而对于支持位域Flags特性的枚举来说,在使用GetDescription方法时,是不能实现的,我们需要对它进行一些改造。

   [Flags]
    public enum Ball
    {

        [Description("足球")]
        FootBall = 1,
        [Description("篮球")]
        BasketBall = 2,
        [Description("乒乓球")]
        PingPang = 4,
    }
    /// <summary>
    /// 枚举类型扩展方法
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 得到Flags特性的枚举的集合
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        static List<Enum> GetEnumValuesFromFlagsEnum(Enum value)
        {
            List<Enum> values = Enum.GetValues(value.GetType()).Cast<Enum>().ToList();
            List<Enum> res = new List<Enum>();
            foreach (var itemValue in values)
            {
                if ((value.GetHashCode() & itemValue.GetHashCode()) != 0)
                    res.Add(itemValue);
            }
            return res;
        }

        /// <summary>  
        /// 获取枚举变量值的 Description 属性  
        /// </summary>  
        /// <param name="obj">枚举变量</param>  
        /// <returns>如果包含 Description 属性,则返回 Description 属性的值,否则返回枚举变量值的名称</returns>  
        public static string GetDescription(this Enum obj)
        {
            string description = string.Empty;
            try
            {
                Type _enumType = obj.GetType();
                DescriptionAttribute dna = null;
                FieldInfo fi = null;
                var fields = _enumType.GetCustomAttributesData();

                if (!fields.Where(i => i.Constructor.DeclaringType.Name == "FlagsAttribute").Any())
                {
                    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;
                    return null;
                }

                GetEnumValuesFromFlagsEnum(obj).ToList().ForEach(i =>
                {
                    fi = _enumType.GetField(Enum.GetName(_enumType, i));
                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                    if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                        description += dna.Description + ",";
                });

                return description.EndsWith(",")
                    ? description.Remove(description.LastIndexOf(','))
                    : description;
            }
            catch
            {
                throw;
            }

        }
    }

它在赋值后,输出是这样的

 Ball ball = Ball.BasketBall | Ball.FootBall;
 Console.WriteLine(ball.GetDescription());

本文转自博客园张占岭(仓储大叔)的博客,原文链接:将不确定变为确定~Flag特性的枚举是否可以得到Description信息,如需转载请自行联系原博主。

目录
相关文章
|
22天前
|
前端开发
let array = [{id:‘001‘,name:‘小新‘,age:5},{ id:‘002‘,name:‘小葵‘]这样数据如何遍历,拿到其中一个值,数组中装对象如何获取其中一个固定的值
let array = [{id:‘001‘,name:‘小新‘,age:5},{ id:‘002‘,name:‘小葵‘]这样数据如何遍历,拿到其中一个值,数组中装对象如何获取其中一个固定的值
|
2月前
|
编译器 C语言 C++
【C++基础】 --- C++相对于C新增bool类型变量
【C++基础】 --- C++相对于C新增bool类型变量
30 1
|
2月前
|
存储 C++ 容器
在C++的set的作用类型
在C++的set的作用类型
19 0
|
8月前
|
存储 JavaScript 前端开发
【JS交互埋坑】事件函数自动将数字字符串String转为数值Number
【JS交互埋坑】事件函数自动将数字字符串String转为数值Number
48 0
cobrautils 使用反射获取 flag 配置, 支持指针字段
cobrautils 使用反射获取 flag 配置, 支持指针字段
103 0
cobrautils 使用反射获取 flag 配置, 支持指针字段
声明了Integer类型的两个数值并且值相等,但为什么返回了false?
声明了Integer类型的两个数值并且值相等,但为什么返回了false?
173 0
|
前端开发 Java
Java 获取Enum枚举中的值,以列表方式返回
Java 获取Enum枚举中的值,以列表方式返回
1866 0
|
存储 程序员 编译器
c++11标准 类默认函数的控制:"=default" 和 "=delete"函数
c++11标准 类默认函数的控制:"=default" 和 "=delete"函数
179 0
|
缓存 Java vr&ar
【BUG日记】【JAVA】使用==判断两个Integer类型的值,发现if语句不起作用(正确做法:使用的判断是equals()去判断)
【BUG日记】【JAVA】使用==判断两个Integer类型的值,发现if语句不起作用(正确做法:使用的判断是equals()去判断)
187 0