Enum.GetName() 表示位字段

本文关键字:字段 表示 GetName Enum | 更新日期: 2023-09-27 18:36:38

如果枚举已用[Flags]属性装饰,则看起来Enum.GetName()不起作用。

该文档未指定与此限制相关的任何内容。

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


以下代码显示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));   // => ""

Enum.GetName() 表示位字段

string s = twoOfThree.ToString();

或:

Console.WriteLine(twoOfThree);

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

为什么不twoOfThree.ToString()

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

如果标志是互斥的,你可以得到这样的名称:

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