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
        }
    }

  • 相关阅读:
    (剑指offer)斐波那契数列
    手写Vue源码 watch的实现
    Vue源码之异步批量任务更新
    手写Vue源码之 依赖收集
    C# 测试代码#if DEBUG使用
    shell脚本编程相关7
    C#中关于ref和out的认识
    shell脚本编程相关6
    shell脚本编程相关5
    shell脚本编程相关4
  • 原文地址:https://www.cnblogs.com/handboy/p/7164002.html
Copyright © 2011-2022 走看看