代码之家  ›  专栏  ›  技术社区  ›  OJay

枚举标志负值

c#
  •  3
  • OJay  · 技术社区  · 6 年前

    有一个 数字( -2147483392 )

    我不明白 它(正确地)投射到旗子上 enum .

    鉴于

    [Flags]
    public enum ReasonEnum
    {
        REASON1 = 1 << 0,
        REASON2 = 1 << 1,
        REASON3 = 1 << 2,
        //etc more flags
        //But the ones that matter for this are
        REASON9 =  1 << 8,
        REASON17 = 1 << 31  
    }
    

    为什么下面的报告正确 REASON9 REASON17 基于 负数

    var reason = -2147483392;
    ReasonEnum strReason = (ReasonEnum)reason;
    Console.WriteLine(strReason);
    

    .NET小提琴 here

    正确地 ,因为这是从COM组件激发的事件原因属性,并且当转换为 枚举 价值观,是的 对的 在它强制转换到的值中(根据该事件)。标志枚举与COM对象的SDK文档一致。COM对象是第三方的,我无法控制这个数字,基于接口,它将始终作为INT提供

    1 回复  |  直到 6 年前
        1
  •  6
  •   Dmitrii Bychenko    6 年前

    最顶层位集( 31日 在你的情况下 Int32 )手段 负数 (见 two's complement

      int reason = -2147483392;
    
      string bits = Convert.ToString(reason, 2).PadLeft(32, '0');
    
      Console.Write(bits);
    

    结果:

      10000000000000000000000100000000
      ^                      ^
      |                      8-th
      31-th
    

    你也有

      -2147483392 == (1 << 31) | (1 << 8) == REASON17 | REASON9