【问题标题】:Unexpected behavior between [Flags] enum : long vs [Flags] enum : ulong[Flags] 枚举之间的意外行为:long 与 [Flags] 枚举:ulong
【发布时间】:2014-03-12 22:49:05
【问题描述】:

编译但不应该

[Flags]
enum TransactionData : long  // 64 bits.  Last bit is sign bit, but I'm putting data there
{
    None = 0,
    Color1 = 1 << 63,
}

错误但不应该

[Flags]
enum TransactionData : ulong  // 64 bits. No sign bit.  Not allowed to put data there
{
    None = 0,
    Color1 = 1 << 63,
}

编译器错误文本:

-2147483648 无法转为ulong

问题:

我预计会发生相反的情况。谁能解释这是为什么?

另外,我如何将此标志属性打印到byte[] 以供检查?

 var eee  = TransactionData.None | TransactionData.Color1
 // How do I convert eee to byte[]?

【问题讨论】:

    标签: c# compiler-construction enums visual-studio-2013 enum-flags


    【解决方案1】:

    请注意,1 &lt;&lt; 63 不是ulong,甚至不是long。编译器将其解释为int。请注意以下示例:

    enum TransactionData : long
    {
        None = 0,
        Color1 = 1 << 31,
        Color2 = 1 << 63,
    }
    
    Console.WriteLine(TransactionData.Color1 == TransactionData.Color2); // True
    

    但是,您可以通过在末尾添加 ul 来强制编译器将其解释为 ulong

    enum TransactionData : ulong
    {
        None = 0,
        Color1 = 1ul << 63,
    }
    

    尽管许多人更喜欢使用大写字母 L,因为小写字母 l 看起来很像数字 1。可以在here 中找到编译器支持的后缀的完整列表。

    另外,我应该指出 1ul &lt;&lt; 63 实际上是 64 位宽(它是一位,移动了 63 位)。

    【讨论】:

    • 有趣的是,我使用 C# 已经 8 年了,刚刚学会了附加字母以将数字转换为不同类型的概念。不知道有多少人和我在同一条船上。
    • 你知道如何将这个 ULong 枚举转换为 Byte[] 概率吗? (无论在 6 分钟内发生什么,ps 都会接受你的。当超时到期时。
    • @makerofthings7 参见BitConverter 类,例如BitConverter.GetBytes((ulong)TransactionData.Color1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2011-12-24
    • 2010-12-22
    • 1970-01-01
    • 2019-06-30
    • 2019-02-16
    相关资源
    最近更新 更多