[Flags]枚举元素上的二进制OR - 为什么不允许简单添加Flags? [关闭]

问题描述 投票:0回答:1
[Flags]
public enum EyeColors
{
    None = 0,
    Blue = 1 << 0,
    Cyan = 1 << 1,
    Brown = 1 << 2,
    Black = 1 << 3,
    Green = 1 << 4,
    Browngreen = 2 | 4
    // Browngreen = Brown | Green
}

Browngreen = 2 | 4
Browngreen = Brown | Green

确实有效

Browngreen = 6

才不是。一个测试的评价就像

EyeColors.Browngreen == (EyeColors.Brown | EyeColors.Green);

如果Browngreen设置为6,则评估为false。


这让我很困惑。我理解二进制文件的方式或是标记位被添加,以便:

0100 : 4 0010 : 2 0110 : 6

那么为什么我刚设置时它不起作用?

Browngreen = 6;
c# enums bitwise-operators enumeration flags
1个回答
0
投票

要组合标志,您需要使用|运营商。将其视为二进制:10000和00100将给出0(无),但10000 |如你所料,00100将给出10100,因此为20。

此外,在“全部”情况下,“无”标志没有意义,我将其删除。

这是一个有效的例子:

[Flags]
public enum EyeColors
{
    None = 0,
    Blue = 1 << 0, // 1
    Cyan = 1 << 1, // 2
    Brown = 1 << 2, // 4
    Black = 1 << 3, // 8
    Green = 1 << 4, // 16
    Browngreen = Brown | Green,
    All = Blue | Green | Brown | Black | Cyan
}

void Main()
{
    EyeColors eyeColors = EyeColors.Brown;
    Console.WriteLine(eyeColors + " (" + (int)eyeColors + ")");

    eyeColors = EyeColors.Brown & EyeColors.Green;
    Console.WriteLine(eyeColors + " (" + (int)eyeColors + ")"); // None

    eyeColors = EyeColors.Brown | EyeColors.Green;  
    Console.WriteLine(eyeColors + " (" + (int)eyeColors + ")"); // Brown green

    eyeColors = (EyeColors)20;
    Console.WriteLine(eyeColors + " (" + (int)eyeColors + ")"); // Brown green also

    eyeColors = EyeColors.All;
    Console.WriteLine(eyeColors + " (" + (int)eyeColors + ")");
}
© www.soinside.com 2019 - 2024. All rights reserved.