zoukankan      html  css  js  c++  java
  • 枚举显示中文问题

    示例:

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

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

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

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

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

    枚举定义很头疼:

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

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

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

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

     

    这时候我们肯定在埋怨:如果是计算机是咱们中国人发明的,也许我们就没这个问题。


    解决方案:

    但是这是没法改变的事实。我们只能加点转换功能变成我们想要的东西了。下面提供解决方案:

    为了方便用户使用, 希望能够找到一种比较好的方法,将枚举转为我们想要的集合。通过反射,得到针对某一枚举类型的描述。

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

    using System;
    using System.ComponentModel;

    public enum TimeOfDay
    {
        [Description(
    "上午")]
        Moning,
        [Description(
    "下午")]
        Afternoon,
        [Description(
    "晚上")]
        Evening,
    };

     

    方法1: 

    获取枚举项+描述
    ///<summary>
    /// 返回 Dic<枚举项,描述>
    ///</summary>
    ///<param name="enumType"></param>
    ///<returns>Dic<枚举项,描述></returns>
    publicstatic 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;
    }

     

    方法2: 获得值和表述的键值对

    获得---值+描述
    ///<summary>
    /// 从枚举类型和它的特性读出并返回一个键值对
    ///</summary>
    ///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
    ///<returns>键值对</returns>
    publicstatic NameValueCollection GetNVCFromEnumValue(Type enumType)
    {
    NameValueCollection nvc
    =new NameValueCollection();
    Type typeDescription
    =typeof(DescriptionAttribute);
    System.Reflection.FieldInfo[] fields
    = enumType.GetFields();
    string strText =string.Empty;
    string strValue =string.Empty;
    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;
    }

    具体用例下载地址:https://files.cnblogs.com/yank/EnumApp.rar

  • 相关阅读:
    值类型和引用类型区别
    json数据类型
    转:不再以讹传讹,GET和POST的真正区别
    简单投票系统学到的一些东西
    jq 全选和反选以及判断那条被选中
    PHP中获取当前页面的完整URL
    jq div鼠标放上、离开马上展开、收缩方法
    js 删除确定
    mysql 存储过程
    js 闭包原理理解
  • 原文地址:https://www.cnblogs.com/yank/p/EnumDisplayInChinese.html
Copyright © 2011-2022 走看看