• 枚举转中文,通过反射方法与描述的方式获取


    示例:

    有人为了显示中文,这样定义枚举吗?

    publicenum TimeOfDay
    {
    上午,
    下午,
    晚上
    };

    这样定义,很别扭,特别是在使用的时候,

    比如,this.Time = TimeOfDay.上午;

    而且你会逐渐发现它的局限性。

    枚举定义很头疼:

    在系统开发中,我们经常使用枚举,但是定义枚举是个头疼的问题。

    按照习惯我们习惯将枚举项定义为英语,但是,在使用的时候,特别针对国内客户的时候,如果显示的英文,则不符合要求,不易于用户使用。

    尽管现在枚举定义也能定义中文枚举项,但在优雅的英文代码中穿插着中语,确实很不爽。如果涉及多语,很难扩展。

    也有人经常用到常量来代替枚举,但这种方法在系统开发中不太可取,具体见:枚举与常量

     

    解决方案:

     

    为了方便用户使用, 希望能够找到一种比较好的方法,将枚举转为我们想要的集合。

    枚举的定义中加入描述,如果要支持多语,则直接修改枚举描述即可。也不用修改其他代码。

    通过反射思想,得到针对某一枚举类型的描述。具体实现起来,有如下代码中的三个不同的的方式。

    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Reflection;
    using System.ComponentModel;
    
    
    namespace EnumApp
    {
        class Program
        {
            static void Main(string[] args)
            {
    
                NameValueCollection nvc = GetNVCFromEnumValue(typeof(TimeOfDay));
    
                Console.WriteLine("1. 反射方式对TimeOfDay结构体的罗列:");
                foreach (string key in nvc.Keys)
                {
                    Console.WriteLine(string.Format(key + ": {0}", nvc[key]));
                }
    
                Console.WriteLine("
    2. 直接方式1,对TimeOfDay结构体的罗列:");
    
                Dictionary<string, string> dic = GetEnumDic(typeof(TimeOfDay));
                foreach (string key in dic.Keys)
                {
                    Console.WriteLine(key + ":{0}", dic[key]);
                }
    
                Console.WriteLine("
    3. 直接方式2,对TimeOfDay结构体中某一项的描述:");
                Console.WriteLine(string.Format(TimeOfDay.Moning.ToString() + ":{0}", GetEnumDes(TimeOfDay.Moning)));
            }
    
            /// <summary>
            /// 从枚举类型和它的特性读出并返回一个键值对
            /// </summary>
            /// <param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
            /// <returns>键值对</returns>
            public static NameValueCollection GetNVCFromEnumValue(Type enumType)
            {
                System.Reflection.FieldInfo[] fields;
                string strText, strValue;
                NameValueCollection nvc = new NameValueCollection();
                Type typeDescription = typeof(DescriptionAttribute);
    
                
                fields = enumType.GetFields();
                
                foreach (FieldInfo field in fields)
                {
                    if (field.FieldType.IsEnum)
                    {
                        strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                        object[] arr = field.GetCustomAttributes(typeDescription, true);
                        if (arr.Length > 0)
                        {
                            DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                            strText = aa.Description;
                        }
                        else
                        {
                            strText = field.Name;
                        }
                        nvc.Add(strValue, strText);
                    }
                }
                return nvc;
            }
            /// <summary>
            /// 返回 Dic<枚举项,描述>
            /// </summary>
            /// <param name="enumType"></param>
            /// <returns>Dic<枚举项,描述></returns>
            public static Dictionary<string, string> GetEnumDic(Type enumType)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                FieldInfo[] fieldinfos = enumType.GetFields();
                foreach (FieldInfo field in fieldinfos)
                {
                    if (field.FieldType.IsEnum)
                    {
                        Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
                        dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description);
                    }
    
                }
    
                return dic;
            }
            /// <summary>
            /// 获得某个枚举项的描述
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            public static string GetEnumDes(object value)
            {
                FieldInfo fieldinfo = value.GetType().GetField(value.ToString());
                Object[] objs = fieldinfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
                if (objs == null || objs.Length == 0)
                {
                    return value.ToString();
                }
                else
                {
                    return ((DescriptionAttribute)objs[0]).Description;
                }
            }
        }
    
        public enum TimeOfDay
        {
            [Description("上午")]
            Moning = 0,
            [Description("下午")]
            Afternoon,
            [Description("晚上")]
            Evening,
        };
    
        //public enum TimeOfDays
        //{
        //    上午,
        //    下午,
        //    晚上
        //};
    }
    View Code

     

    或者通过下载文件,直接进行测试。EnumDecriptionGet.rar

     

     

     

    参考文章

     

    枚举显示中文问题

     

  • 相关阅读:
    解决is not a supported wheel on this platform-解决pip has no attribute pep425tags-解决网上旧教程不适用的问题
    语音信号实验1-基于时域分析技术的语音识别
    解决 ModuleNotFoundError: No module named 'pip'
    Typecho如何上传模板和插件
    获取图片的URL链接(Typecho修改背景图片等都需要URL链接)
    ubuntu云服务器安装anaconda+jupyter配置
    ORACLE用户密码过期啦
    关于Nacos启动报如下错:nacos no javac in (usr/lib/jvm-1.8.0)
    记录一次华为云服务器给根目录扩容
    记录一次NFS快照es集群索引备份
  • 原文地址:https://www.cnblogs.com/arxive/p/6285718.html
Copyright © 2020-2023  润新知