C#中枚举的使用

2021-01-19 02:38

阅读:640

标签:==   类型   eva   eval   collect   lin   nat   sorted   for   

枚举大家都不陌生,但是最近看到有的人,还在是页面上写死,如果枚举增减时,还要去页面去手动修改,今天我们来看看枚举的处理方式,这里说一下,我用的测试程序是.net core 3.1。

不多墨迹,直接上代码:

定义枚举:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace ConsoleApp1
{
    public enum Status
    {
        [Description("已删除")]
        Deleted = -1,

        [Description("未处理")]
        Init = 0,

        [Description("正常")]
        Normal = 1
    }
}

枚举的辅助类,这里说明一下,我是通过获取枚举上的特性来处理的:

EnumUtil.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;

namespace ConsoleApp1
{
    public static class EnumUtil
    {
        /// 
        /// 获取枚举的描述
        /// 
        /// 
        /// 
        public static string GetDesc(Enum obj)
        {
            string objName = obj.ToString();
            Type t = obj.GetType();
            FieldInfo fi = t.GetField(objName);
            if (fi == null)
                return objName;
            DescriptionAttribute[] arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (arrDesc.Length > 0)
                return arrDesc[0].Description;
            else
                return objName;
        }
        /// 
        /// 获取枚举的键值对集合
        /// 
        /// 
        /// 
        public static Dictionaryint, string> GetEnumIntNameDict(Enum e)
        {
            return GetEnumNameValueDict(e, (Object o) => { return Convert.ToInt32(o); });
        }
        public static Dictionarystring> GetEnumNameValueDict(Enum e, Converter convert)
        {
            Type enumType = e.GetType();
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("参数必须是枚举类型", "enumType");
            }

            FieldInfo[] fields = enumType.GetFields();

            if (fields != null)
            {
                Dictionarystring> dict = new Dictionarystring>();

                foreach (FieldInfo f in fields)
                {
                    if (f.Name.EndsWith("__")) continue;

                    DescriptionAttribute[] attrs = (DescriptionAttribute[])f.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    string name = f.Name;
                    if (attrs != null && attrs.Length == 1)
                    {
                        name = attrs[0].Description;
                    }
                    TOutput val = convert(f.GetValue(e));
                    dict.Add(val, name);
                }
                return dict;
            }

            return null;
        }
        /// 
        /// 获取枚举的键值对集合
        /// 
        /// 
        /// 
        public static Dictionarystring, string> GetEnumVarNameDict(Enum e)
        {
            Type enumType = e.GetType();
            if (!enumType.IsEnum)
            {
                throw new ArgumentException("参数必须是枚举类型", "enumType");
            }

            FieldInfo[] fields = enumType.GetFields();

            if (fields != null)
            {
                Dictionarystring, string> dict = new Dictionarystring, string>();

                foreach (FieldInfo f in fields)
                {
                    if (f.Name.EndsWith("__")) continue;

                    DescriptionAttribute[] attrs = (DescriptionAttribute[])f.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    string name = f.Name;
                    if (attrs != null && attrs.Length == 1)
                    {
                        name = attrs[0].Description;
                    }
                    dict.Add(f.Name, name);
                }
                return dict;
            }

            return null;
        }

        private static SortedListstring> enumDesciptionDict = new SortedListstring>();
        /// 
        /// 获取枚举的描述
        /// 
        /// 
        /// 
        public static string GetDescription(this Enum value)
        {
            string description = string.Empty;
            if (enumDesciptionDict.TryGetValue(value, out description)) return description;

            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute == null)
                enumDesciptionDict[value] = value.ToString();
            else
                enumDesciptionDict[value] = attribute.Description;
            return enumDesciptionDict[value];
        }
        /// 
        /// 获取特性
        /// 
        /// 
        /// 
        public static DescriptionAttribute GetAttribute(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            return Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        }
    }
}

定义一个调用类,当然你也可以直接调用:

CommonEnumsDict.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1
{
    public class CommonEnumsDict
    {

        public static readonly Dictionaryint, string> StatusDict;
        public static readonly Dictionarystring, string> StatusStrDict;
        static CommonEnumsDict()
        {
            StatusDict = EnumUtil.GetEnumIntNameDict(Status.Normal);
            StatusStrDict = EnumUtil.GetEnumVarNameDict(Status.Normal);
        }
    }
}

最后调用:

Program.cs

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in CommonEnumsDict.StatusDict)
            {
                Console.WriteLine("key:" + item.Key + ",value:" + item.Value);
            }
            Console.WriteLine("--------------------------");
            var PayValues = Enum.GetValues(typeof(Status));
            foreach (var v in PayValues)
            {
                var name = EnumUtil.GetDesc((Status)v);
                Console.WriteLine("key:" + (int)v + ",value:" + name);

            }
            Console.WriteLine("--------------------------");
            foreach (var item in CommonEnumsDict.StatusStrDict)
            {
                Console.WriteLine("key:" + item.Key + ",value:" + item.Value);
            }
            var del = Status.Deleted.GetAttribute();
            Console.WriteLine("del:" + del.Description);
            Console.ReadLine();
        }
    }
}

结果:

key:-1,value:已删除
key:0,value:未处理
key:1,value:正常
--------------------------
key:0,value:未处理
key:1,value:正常
key:-1,value:已删除
--------------------------
key:Deleted,value:已删除
key:Init,value:未处理
key:Normal,value:正常
del:已删除

你最喜欢的代码:点击下载

C#中枚举的使用

标签:==   类型   eva   eval   collect   lin   nat   sorted   for   

原文地址:https://www.cnblogs.com/itmu89/p/12164023.html


评论


亲,登录后才可以留言!