zoukankan      html  css  js  c++  java
  • 枚举类字典代码 草稿

    原文发布时间为:2011-03-09 —— 来源于本人的百度文章 [由搬家工具导入]

    EnumDescriptionAttribute.cs

    using System;


    /// <summary>
    /// Provides a description for an enumerated type.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public sealed class EnumDescriptionAttribute : Attribute
    {
        private readonly string description;

        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <param name="description"></param>
        public EnumDescriptionAttribute(string description)
        {
            this.description = description;
        }

        public string Description
        {
            get { return description; }
        }
    }

    EnumHelper.cs

    using System;
    using System.Reflection;

    public static class EnumHelper
    {
        /// <summary>
        /// Gets the <see cref="DescriptionAttribute" /> of an <see cref="Enum" />
        /// type value.
        /// </summary>
        /// <param name="value">The <see cref="Enum" /> type value.</param>
        /// <returns>A string containing the text of the
        /// <see cref="DescriptionAttribute"/>.</returns>
        public static string GetDescription(Enum value)
        {
            if (value == null)
            {
                return "";
            }
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            EnumDescriptionAttribute[] attributes = null;
            if (fieldInfo != null)
            {
                attributes = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
            }
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            return "";
        }
    }

    Program.cs

    using System;

    namespace TestEnum
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                Console.WriteLine("{0}", EnumHelper.GetDescription(SimpleEnum.Today));
                Console.WriteLine("{0}", EnumHelper.GetDescription((SimpleEnum)(2)));
                Console.ReadLine();
            }
        }

        public enum SimpleEnum
        {
            [EnumDescription("今天")]
            Today,
            [EnumDescription("明天")]
            Tomorrow,
            [EnumDescription("后天")]
            AfterTomorrow
        }
    }

  • 相关阅读:
    UC_online在线抽奖_新浪UC(Tab页功能)
    Asp.Net上传文件示例(保存文件路径到数据库)
    中国十大美丽女主播
    行业应用软件项目经理三步曲
    TVB十大女星比美十大名花
    SQLServer和Oracle常用函数对比
    如何撰写商业计划
    带农历的日历
    ASP+VML制作统计图的源程序
    Winamp网页播放器
  • 原文地址:https://www.cnblogs.com/handboy/p/7164002.html
Copyright © 2011-2022 走看看