枚举类字典代码 草稿

原文发布时间为: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
    }
}

原文地址:https://www.cnblogs.com/handboy/p/7164002.html