Enum.GetName()的位字段?

时间:2012-06-08 12:38:24

标签: c# parsing enums bit-fields

如果枚举已使用Enum.GetName()属性进行修饰,则[Flags]似乎不起作用。

documentation 未指定与此限制相关的任何内容。

我注意到调试器能够显示类似 Tree |的内容水果即可。有没有办法检索描述组合标志的文本字符串?


以下代码显示Red

public enum FavoriteColor
{
    Red,
    Blue,
    WeirdBrownish,
    YouDoNotEvenWantToKnow,
}

var color = FavoriteColor.Red;
Console.WriteLine(Enum.GetName(typeof(FavoriteColor), color));   // => "Red"

虽然这个没有输出任何东西......

[Flags]
public enum ACherryIsA
{
    Tree = 1,
    Fruit = 2,
    SorryWhatWasTheQuestionAgain = 4,
}

var twoOfThree = ACherryIsA.Fruit | ACherryIsA.Tree;
Console.WriteLine(Enum.GetName(typeof(ACherryIsA), twoOfThree));   // => ""

3 个答案:

答案 0 :(得分:7)

string s = twoOfThree.ToString();

或:

Console.WriteLine(twoOfThree);

如果要手动执行此操作,请将值拆分为位,并测试需要添加哪些标志才能生成该标记。一点编码,但不多。

答案 1 :(得分:4)

为什么不twoOfThree.ToString()

twoOfThree等于3,而ACherryIsA没有与此值相关的枚举成员......

答案 2 :(得分:0)

如果标志是互斥的,则可以得到如下名称:

((ACherryIsA[])Enum.GetValues(typeof(ACherryIsA)))
.Where(e => twoOfThree.HasFlag(e))

演示:

var twoOfThree = ACherryIsA.Fruit | ACherryIsA.Tree;
Console.WriteLine(
    "Name: " + String.Join(
        ",", 
        ((ACherryIsA[])Enum.GetValues(typeof(ACherryIsA)))
        .Where(e => twoOfThree.HasFlag(e))
    )
);   // => Name: Tree,Fruit

但是如果标志重叠,这会产生奇怪的结果:

[Flags]
public enum ACherryIsA
{
    Tree = 1,
    Fruit = 2,
    SorryWhatWasTheQuestionAgain = 4,
    FruitTree = Tree | Fruit,
}

public static void Main()
{
    var twoOfThree = ACherryIsA.Fruit | ACherryIsA.Tree;
    Console.WriteLine(
        "Name: " + String.Join(
            ",", 
            ((ACherryIsA[])Enum.GetValues(typeof(ACherryIsA)))
            .Where(e => twoOfThree.HasFlag(e))
        )
    );   // => Name: Tree,Fruit,FruitTree
}