Switch 语句包含多个具有相同标签值的情况,但它不

Switch Statement contains multiple cases with same label value, except it doesn't

我有这个枚举:

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 2 ^ 1,
    Value2 = 2 ^ 2,
    Value3 = 2 ^ 3,
    Value4 = 2 ^ 4
}

现在我想在这个枚举上使用一个开关:

public void SwitchThroughEnum(MyEnum myEnum)
{
    switch (myEnum)
    {
        case MyEnum.NegativeValue:
            break;
        case MyEnum.Value0:
            break;
        case MyEnum.Value1:
            break;
        case MyEnum.Value2:
            break;
        case MyEnum.Value3:
            break;
        case MyEnum.Value4:
            break;
        default:
            break;
    }
}

但我无法编译它,因为 Visual Studio 告诉我“switch 语句包含多个标签值为‘0’的 case”。我不知道为什么会这样。

编辑:是否有可能以仅使用 1、2 等的幂的方式创建枚举?有时我有超过 30 个条目的枚举,计算和写入数字是在消磨时间

这是布尔异或运算符Microsoft docs

Exclusive or or exclusive disjunction is a logical operation that outputs true only when inputs differ (one is true, the other is false)

所以2 ^ 2确实是0

The ^ operator computes the bitwise logical exclusive OR, also known as the bitwise logical XOR, of its integral operands.

所以在位逻辑中10 XOR 10 = 0

我的猜测是你想用2对2的幂,那你为什么不直接做呢?

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 2,
    Value2 = 4,
    Value3 = 8,
    Value4 = 16
}

您使用的 Logical exclusive OR operator ^ 不是数的幂。

C# 没有幂运算符,您不能使用 Math.Pow,因为它不是常量,好吧,它 returns 一个 double.

也许您需要二进制文字:

public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 0b0000001,
    Value2 = 0b0000010,
    Value3 = 0b0000100,
    Value4 = 0b0001000,
}

public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    Value4 = 8,
}

I sometimes have enums with way more then 30 entries, and calculating and writing the numbers is time killing

是的,只是 bit shift

[Flags]
public enum MyEnum
{
    NegativeValue = -1,
    Value0 = 0,
    Value1 = 1,
    Value2 = 2 << 0,
    Value3 = 2 << 1,
    Value4 = 2 << 2
}