代码改变世界

让枚举显示中文描述信息,利用 Attribute

2011-10-16 14:59  音乐让我说  阅读(482)  评论(0编辑  收藏  举报

这是上一篇文章“利用反射得到枚举描述”的一个延续。

 

更新说明:

推荐 Enums.NET 开源组件处理 C# 枚举。这里是我整理的 Demo:https://files.cnblogs.com/files/Music/Enums.NET_Demo_VeryGood.rar

 

 

代码如下:

Program.cs

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

namespace EnumAddChineseDescription
{
    class Program
    {
        static void Main(string[] args)
        {
            //ShowResponseStatus((ReponseStatus)8); // 抛出异常
            ShowResponseStatus(ReponseStatus.Success); // 打印 “成功”
            ShowResponseStatus(ReponseStatus.Unknown); // 打印 “Unknown”
            Console.WriteLine(ScoreLevel.Primary.ToDescription()); // 打印 “初级”
            Console.WriteLine(ScoreLevel.High.ToDescription()); // 打印 “”
            Console.WriteLine(ScoreLevel.Unknown.ToDescription()); // 打印 “Unknown”
        }

        static void ShowResponseStatus(ReponseStatus status)
        {
            if (!Enum.IsDefined(typeof(ReponseStatus), status))
            {
                throw new ArgumentOutOfRangeException("status", "未找到该枚举!");
            }
            Console.WriteLine(status.ToChineseDescription());
        }
    }
}

 

ChineseDescriptionAttribute.cs

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

namespace EnumAddChineseDescription
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class ChineseDescriptionAttribute : Attribute
    {
        private string _text;

        public string Text
        {
            get
            {
                return _text;
            }
        }

        public ChineseDescriptionAttribute(string text)
        {
            this._text = text;
        }
    }
}

  

EnumExtensions.cs

using System;
using System.Reflection;
using System.ComponentModel;

namespace EnumAddChineseDescription
{
    /// <summary>
    /// 扩展 Enum 类
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 显示中文的描述,自定义 Attribute 的类型应该为 ChineseDescriptionAttribute
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToChineseDescription(this Enum enumeration)
        {
            // 假设我们传入的参数是:ReponseStatus.Success
            Type type = enumeration.GetType(); // 得到枚举的类型:到底是哪个枚举
            MemberInfo[] memInfos = type.GetMember(enumeration.ToString()); // 得到枚举的字段,可能零个或一个或多个
            if (memInfos != null && memInfos.Length > 0)
            {
                object[] customEnumDesc = memInfos[0].GetCustomAttributes(typeof(ChineseDescriptionAttribute), false); // 得到枚举的自定义 Attribute
                if (customEnumDesc != null && customEnumDesc.Length > 0)
                {
                    return ((ChineseDescriptionAttribute)customEnumDesc[0]).Text;
                }
            }
            return enumeration.ToString();
        }

        /// <summary>
        /// 显示枚举的描述,自定义 Attribute 的类型应该为 System.ComponentModel.DescriptionAttribute
        /// </summary>
        /// <param name="enumeration"></param>
        /// <returns></returns>
        public static string ToDescription(this Enum enumeration)
        {
            Type type = enumeration.GetType();
            MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            return enumeration.ToString();
        }
    }
}

  

ReponseStatus.cs

namespace EnumAddChineseDescription
{
    public enum ReponseStatus
    {
        [ChineseDescriptionAttribute("成功")]
        Success = 1,

        [ChineseDescriptionAttribute("错误")]
        Error = 2, 

        Unknown = 3,

        [ChineseDescriptionAttribute("失败")]
        Fail = 4
    }
}

  

ScoreLevel.cs

using System.ComponentModel;

namespace EnumAddChineseDescription
{
    public enum ScoreLevel
    {
        [Description("初级")]
        Primary = 1,

        [Description("中级")]
        Intermediate = 2,

        [Description()] // 这里我们故意不填写
        High = 3, 

        Unknown = 4
    }
}

  

代码下载:EnumAddChineseDescription.rar

谢谢浏览!