枚举超过2 ^ 32的标志 [英] Enum flags over 2^32

查看:111
本文介绍了枚举超过2 ^ 32的标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用Enum标志.枚举可以包含大约50个以上的值,因此值最多可以达到2 ^ 50.我只是想知道,我可以使用Math.Pow(2, variable)来计算这些吗?

I am using Enum flags in my application. The Enum can have around 50+ values, so values go up to 2^50. I was just wondering, can I use Math.Pow(2, variable) to calculate these?

当我尝试这样做时,我得到一个恒定值编译时错误.除了手动计算这些2的幂并将其放入之外,还有其他方法吗?

When I try to do that I get a constant value compile-time error. Is there another way, other than calculating these powers of 2 manually and putting it in?

这是我在做什么:

[Flags]
internal enum RiskStates : long
    {
        None = 0,
        AL = Convert.ToInt64(Math.Pow(2,0)),
        AK = 2,
        AZ = 4,
        AR = 8,
        CA = 16,
        CO = 32,
        CT = 64,
        DC = 128,
        DE = 256,
        FL = 512,
        GA = 1024,
        HI = 2048,
        ID = 4096,
        IL = 8192,
        IN = 16384,
        IA = 32768,
        KS = 65536,
        KY = 131072,
        LA = 262144,
        ME = 524288,
        MD = 1048576,
        MA = 2097152,
        MI = 4194304
}

推荐答案

当我尝试这样做时,我得到一个恒定值编译时错误.

如果您使用L后缀将其强制为long文字,您实际上会没事-但是手动指定它们仍然不是理想的选择. (阅读代码时显然不是正确的".)

You'd actually be okay if you used the L suffix to force it to be a long literal - but it's still not ideal to have to specify them all manually. (It's not "obviously correct" when reading the code.)

您不能使用Math.Pow,因为表达式必须是编译时常量-但您可以使用位移:

You can't use Math.Pow as the expression has to be a compile-time constant - but you can use bit-shifting:

None = 0,
AL = 1L << 0,
AK = 1L << 1,
AZ = 1L << 2

等我认为反正这更容易理解:)

etc. I'd argue that's more readable anyway :)

这篇关于枚举超过2 ^ 32的标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆