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

12 浏览
0 Comments

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

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

using System;
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(Colors.All);// 红色,黄色,蓝色,绿色
                var noRed = Colors.All & ~Colors.Red;
                Console.WriteLine(noRed);// 黄色,蓝色,绿色
                Console.ReadLine();
            }
        }
        [Flags]
        enum Colors
        {
            None=0,
            Red= 1<<0,
            Yellow = 1<<1,
            Blue= 1<<2,
            Green=1<<3,
            All = Red | Yellow| Blue | Green
        }
    }

0
0 Comments

问题的原因是,枚举类型在默认情况下只能输出枚举的名称,而不是实际的值。解决方法是使用描述属性为枚举添加描述,在输出时获取描述属性的值。

为了实现你的需求,我认为最好的方法是在枚举中使用描述属性。以下是示例代码可以帮助你实现需求:

[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
}
// 创建一个辅助类和函数来获取枚举值的描述
using System;
using System.ComponentModel;
using System.Reflection;
public static class EnumHelper
{
    /// 
    /// 获取枚举的描述,例如:
    /// [Description("Bright Pink")]
    /// BrightPink = 2,
    /// 当你传入枚举时,它会返回描述
    /// 
    /// 枚举类型
    /// 表示友好名称的字符串
    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();
    }
}
// 现在可以使用这个函数来获取枚举值的描述
Console.WriteLine(EnumHelper.GetDescription(Colors.All));

这样可以实现你的需求,但是可能比较难以重构。

0