如何让带有标志输出的枚举全部具有实际值?

时间:2016-09-09 04:45:33

标签: c# enums

考虑以下代码,如何让Console.WriteLine(Colors.All)输出"红色,黄色,蓝色,绿色",而不是"所有"?

using System;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(Colors.All);// All
                var noRed = Colors.All & ~Colors.Red;
                Console.WriteLine(noRed);// Yellow, Blue, Green
                Console.ReadLine();
            }
        }

        [Flags]
        enum Colors
        {
            None=0,
            Red= 1<<0,
            Yellow = 1<<1,
            Blue= 1<<2,
            Green=1<<3,
            All = Red | Yellow| Blue | Green
        }
    }

1 个答案:

答案 0 :(得分:0)

为了在您的案例中获得理想的结果,我认为最好的方法是为您的枚举使用description属性。查看我的代码,它将帮助您实现所需的目标。

[Flags]
    enum Colors
    {
        [Description("None")]
        None=0,
        [Description("Red")]
        Red= 1<<0,
        [Description("Burnt Yellow")]
        Yellow = 1<<1,
        [Description("Blue")]
        Blue= 1<<2,
        [Description("Green")]
        Green=1<<3,
        [Description("Red | Yellow| Blue | Green")]
        All = 99
    }

// Now create helper class and function to get enum description for associated value.

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


public static class EnumHelper
{
    /// <summary>
    /// Retrieve the description on the enum, e.g.
    /// [Description("Bright Pink")]
    /// BrightPink = 2,
    /// Then when you pass in the enum, it will retrieve the description
    /// </summary>
    /// <param name="en">The Enumeration</param>
    /// <returns>A string representing the friendly name</returns>
    public static string GetDescription(Enum en)
    {
        Type type = en.GetType();

        MemberInfo[] memInfo = type.GetMember(en.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 en.ToString();
    }

}



//Now use this function to get attribute for your enum value.
Console.WriteLine(EnumHelper.GetDescription(Colors.All));