枚举常用操作扩展方法


完整代码在笔记结尾

获取枚举描述

public static string GetEnumDescription(this Enum en)
        {
            var type = en.GetType(); //获取类型
            var memberInfos = type.GetMember(en.ToString()); //获取成员
            if (memberInfos.Any())
            {
                if (memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attrs && attrs.Length > 0)
                {
                    return attrs[0].Description; //返回当前描述
                }
            }

            return en.ToString();
        }

获取枚举Display特性的名称

原理与获取Description描述是一样的,都是先获取类型,再通过GetMember方法获取到每个成员到数组中,最后通过DisplayAttribute获取其属性,DisplayAttribute这个特性里面的属性可以在编写枚举成员时通过注解写入

[Display(Name = "红", GroupName = "纯色")]
[Description("红色")]
Red = 1,
[Display(Name = "橙红", GroupName = "混合色")]
[Description("橙红色")]
OriginRed = 2

获取Display特性下的属性的代码例子:

public static string GetDisplay(this Enum en)
        {
            var type = en.GetType(); //获取类型
            var memberInfos = type.GetMember(en.ToString()); //获取成员
            if (memberInfos.Any())
            {
                if (memberInfos[0].GetCustomAttributes(typeof(DisplayAttribute), false) is DisplayAttribute[] attrs && attrs.Length > 0)
                {
                    //var groupName= attrs[0].GroupName;
                    //var order = attrs[0].Order;
                    return attrs[0].Name; //返回当前描述
                }
            }

            return en.ToString();
        }

获取枚举列表以枚举值作为Key

public static readonly ConcurrentDictionary> EnumNameValueDict = new ConcurrentDictionary>();

public static Dictionary GetEnumDictionary(this Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new Exception("传入的类型非枚举(Enum)类型");
            }

            var names = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary();
            if (names.Count == 0)
            {
                names = GetDictionaryItems(enumType);
                EnumNameValueDict[enumType] = names;
            }
            return names;
        }

根据枚举值获取枚举成员

public static string ToMemberByValue(this int value, Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new Exception("给定的类型非枚举(Enum)类型");
            }

            var nvc = new NameValueCollection();
            var fields = enumType.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    nvc.Add(strValue, field.Name);
                }
            }
            return nvc[value];
        }

完整扩展类及使用示例

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace 枚举
{
    /// 
    /// 枚举扩展类
    /// 
    public static class EnumExtension
    {
        public static readonly ConcurrentDictionary> EnumNameValueDict = new ConcurrentDictionary>();
        private static readonly ConcurrentDictionary> EnumValueNameDict = new ConcurrentDictionary>();

        /// 
        ///  获取枚举对象Key与显示名称的字典
        /// 
        /// 枚举类型
        /// 以值为Key,显示名称为Value的字典
        /// 非枚举类型
        public static Dictionary GetEnumDictionary(this Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new Exception("给定的类型非枚举(Enum)类型");
            }

            var names = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary();
            if (names.Count == 0)
            {
                names = GetDictionaryItems(enumType);
                EnumNameValueDict[enumType] = names;
            }
            return names;
        }

        /// 
        /// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
        /// 
        /// 
        /// 
        public static Dictionary GetEnumDescriptionAndValue(this Type enumType)
        {
            return Enum.GetValues(enumType)
                .Cast()
                .ToDictionary(e =>
                GetEnumDescription(e as Enum),
                e => (int)e);
        }

        /// 
        /// 获取枚举对象的值内容
        /// 
        /// 
        /// 
        /// 
        public static int GetEnumValue(this Type enumType, string name)
        {
            if (!enumType.IsEnum)
            {
                throw new Exception("给定的类型非枚举(Enum)类型");
            }

            Dictionary enumDict = GetValueNameItems(enumType);
            return enumDict.ContainsKey(name) ? enumDict[name] : enumDict.Select(d => d.Value).FirstOrDefault();
        }

        /// 
        /// 根据枚举成员获取Description描述
        /// 
        /// 
        /// 
        public static string GetEnumDescription(this Enum en)
        {
            var type = en.GetType(); //获取类型
            var memberInfos = type.GetMember(en.ToString()); //获取成员
            if (memberInfos.Any())
            {
                if (memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attrs && attrs.Length > 0)
                {
                    return attrs[0].Description; //返回当前描述
                }
            }

            return en.ToString();
        }

        /// 
        /// 根据枚举成员获取Display的属性Name
        /// 
        /// 
        public static string GetEnumDisplay(this Enum en)
        {
            var type = en.GetType(); //获取类型
            var memberInfos = type.GetMember(en.ToString()); //获取成员
            if (memberInfos.Any())
            {
                if (memberInfos[0].GetCustomAttributes(typeof(DisplayAttribute), false) is DisplayAttribute[] attrs && attrs.Length > 0)
                {
                    return attrs[0].Name; //返回当前描述
                }
            }

            return en.ToString();
        }

        /// 
        /// 根据枚举值获取枚举成员
        /// 
        /// 枚举值
        /// 枚举类型
        /// 
        public static string ToMemberByValue(this int value, Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new Exception("给定的类型非枚举(Enum)类型");
            }

            var nvc = new NameValueCollection();
            var fields = enumType.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    nvc.Add(strValue, field.Name);
                }
            }
            return nvc[value];
        }

        #region 私有操作方法
        private static Dictionary GetDictionaryItems(Type enumType)
        {
            var enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            var names = new Dictionary(enumItems.Length);
            foreach (FieldInfo enumItem in enumItems)
            {
                int intValue = (int)enumItem.GetValue(enumType);
                names[intValue] = enumItem.Name;
            }

            return names;
        }

        private static Dictionary GetValueNameItems(Type enumType)
        {
            var enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            var values = new Dictionary(enumItems.Length);
            foreach (var enumItem in enumItems)
            {
                values[enumItem.Name] = (int)enumItem.GetValue(enumType);
            }

            return values;
        }

        /// 
        /// 根据枚举类型得到其所有的 值 与 枚举定义字符串 的集合
        /// 
        /// 
        /// 
        private static NameValueCollection GetEnumStringFromEnumValue(Type enumType)
        {
            var nvc = new NameValueCollection();
            var fields = enumType.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    nvc.Add(strValue, field.Name);
                }
            }

            return nvc;
        }

        #endregion
    }
}


使用示例:

public class Program
    {
        static void Main(string[] args)
        {
            //使用示例:
            var dic1 = typeof(MyEnum).GetEnumDictionary(); //获取所有成员
            var dic2 = typeof(MyEnum).GetEnumDescriptionAndValue();  //获取所有成员(描述和值)
            var memberVal = typeof(MyEnum).GetEnumValue("Red");  //根据成员字符串获取枚举值
            var desc = MyEnum.Green.GetEnumDescription();  //根据枚举成员获取描述
            var displayStr = MyEnum.Green.GetEnumDisplay();  //根据枚举成员获取显示名称
            var member = 2.ToMemberByValue(typeof(MyEnum));  //根据枚举值获取枚举成员
        }

        public enum MyEnum
        {
            [Display(Name = "红", GroupName = "纯色")]
            [Description("红色")]
            Red = 1,
            [Display(Name = "绿")]
            [Description("绿色")]
            Green = 2,
            [Display(Name = "蓝")]
            [Description("蓝色")]
            Blue = 3,

        }
    }