简体   繁体   中英

Enum.GetName() for bit fields?

It looks like Enum.GetName() doesn't work if the enum has been decorated with a [Flags] attribute.

The documentation doesn't specify anything related to this limitation.

I've noticed the debugger is able to display something like Tree | Fruit . Is there a way to retrieve the text string describing the combined flags?


Following code display Red .

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

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

Whereas this one doesn't output anything....

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

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

or:

Console.WriteLine(twoOfThree);

If you want to do it manually, split the value into bits, and test what flags you need to add to make that flag. A bit of coding, but not much.

Why not twoOfThree.ToString() ?

twoOfThree equals 3, and ACherryIsA has no related enum member for this value...

If the flags are mutually exclusive, you can get the names like this:

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

Demo:

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

But this behaves weirdly if the flag has overlap:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM