c# - FlagsAttribute 枚举问题

标签 c# .net enum-flags

所以我正在构建一个 MSNP(windows live messenger)客户端。我有这个功能列表

public enum UserCapabilities : long
{
    None = 0,
    MobileOnline = 1 << 0,
    MSN8User = 1 << 1,
    RendersGif = 1 << 2,
    ....
    MsgrVersion7 = 1 << 30,
    MsgrVersion8 = 1 << 31,
    MsgrVersion9 = 1 << 32,
}

完整列表在这里 http://paste.pocoo.org/show/383240/

服务器将每个用户的能力作为一个长整数发送给客户端,我将其转换为 UserCapabilities

capabilities = Int64.Parse(e.Command.Args[3]);
user._capabilities = (UserCapabilities)capabilities;

这很好,至少有一个用户(能力值为 1879474220),我可以做到

Debug.WriteLine(_msgr.GetUser(usr).Capabilities);

这将输出

RendersGif, RendersIsf, SupportsChunking, IsBot, SupportsSChannel, SupportsSipInvite, MsgrVersion5, MsgrVersion6, MsgrVersion7

但是对于另一个具有 (3055849760) 能力值的用户,当我执行相同操作时,我只会输出相同的数字

3055849760

我希望看到的是功能列表,就像其他用户一样。

我确信发生这种情况有一个非常正当的理由,但无论我多么努力地向 Google 提出这个问题,我都找不到答案。

请帮助我:)

最佳答案

移位运算符的定义意味着只有最低5位用于32位数字,只有前6位用于64位;含义:

1 << 5

相同
1 << 37

(都是32)

通过制作:

MsgrVersion9 = 1L << 32

您将其设置为 64 位数字,这就是@leppie 的修复工作的原因;否则 <<被认为是第一个(并注意 1<<32 1<<0 相同,即 1 ) , 和 then 结果 1转换为 long ;所以它仍然是1 .

来自 ECMA 规范中的 §14.8:

For the predefined operators, the number of bits to shift is computed as follows:

  • When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.
  • When the type of x is long or ulong, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F.

If the resulting shift count is zero, the shift operators simply return the value of x.

Shift operations never cause overflows and produce the same results in checked and unchecked context

关于c# - FlagsAttribute 枚举问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893923/

相关文章:

c# - 在 C# 中规范化目录名称

c# - 生成日期时间(exp:09.02.2009)到字符串日期(exp:Monday)

.net - 像信用卡持有功能一样用 Paypal 持有付款

c# - 可以将 "All"项添加到 Flags 枚举吗?

c# - XML 序列化 + 命名空间 (C#)

c# - 如何从左向右移动入侵者

c# - 将字符串转换为命令?

c# - UWP - 通过套接字将网络摄像头流式传输到 MediaElement - 图片损坏?

c# - 如果我们按顺序声明 [Flags] 枚举会发生什么?

c# - 使用复选框来回发带有标志的枚举