【问题标题】:Cannot interpret state of this BitVector32无法解释此 BitVector32 的状态
【发布时间】:2021-01-12 07:15:24
【问题描述】:

我现在正在调试一些代码(VS 2019,.NET Framework 4.7.2),在断点处停止,使用 立即窗口 来评估变量。我有一个BitVector32,我不了解它的状态。以下是IW的内容:

stillInHand.ToString()
"BitVector32{00000000000000000000000000001100}"
stillInHand
{BitVector32{00000000000000000000000000001100}}
    Data: 12
stillInHand[0]
true
stillInHand[1]
false
stillInHand[2]
false
stillInHand[3]
false
stillInHand[4]
true
stillInHand[5]
false
stillInHand[6]
false
stillInHand[7]
false

没有调用任何Create* 方法,并且stillInHand 是使用BitVector32(Int32) ctor 创建的。索引 2 和 3 不应该是 true 而其余的不是 false

【问题讨论】:

    标签: c# visual-studio debugging visual-studio-debugging bitvector


    【解决方案1】:

    其实,这个问题与对BitVector32[ ]的索引的理解有关。

    首先stillInHand[1] 并不意味着获得 stillInHand(BitVector32) 的第二位。它代表这个动作:使用00 00 … 00 01 与 StillInHand(BitVector32) 执行&(AND) 操作。

    举个例子stillInHand(BitVector32)00 00 00 00 00 … 00 00 00 11 00100 00 00 00 00 … 00 00 00 00 01。然后执行&(AND) 操作。

    00 00 00 00 00 … 00 00 00 11 00        12      &(AND)
    
    00 00 00 00 00 … 00 00 00 00 01       `1`
    
    --------------------------------------------
    
    00 00 00 00 00 … 00 00 00 00 00
    

    并且可以看到最后一位(关注索引值1)从1变为0,所以结果会是false,如果你输出或者看到@987654336的结果@。

    所以,对于stillInHand[2],你可以看到

    00 00 00 00 00 … 00 00 00 11 00        12      &(AND)
    
    00 00 00 00 00 … 00 00 00 00 10        2
    
    --------------------------------------------
    
    00 00 00 00 00 … 00 00 00 00 00
    

    倒数第二位(关注索引值2)从1变为0,所以结果也是false

    对于stillInHand[8],你可以看到

    00 00 00 00 00 … 00 00 00 11 00        12      &(AND)
    
    00 00 00 00 00 … 00 00 00 10 00        8
    
    --------------------------------------------
    
    00 00 00 00 00 … 00 00 00 10 00
    

    倒数第四位(关注索引值8)不变,保持为1,所以结果为true

    其实,如果你从这里分析源代码:Reference Source,你可以看到这些代码:

    /// <devdoc>
    ///    <para>Gets or sets a value indicating whether all the specified bits are set.</para>
    /// </devdoc>
    
    public bool this[int bit] {
       get {
                return (data & bit) == (uint)bit; 
                //clear other bits (to 0) through the AND operation of the data and mask.
                //If the result of the operation is equal to the mask, return true.
                //Otherwisse, return false.
           }
       set {
                if (value) {
                    data |= (uint)bit;
                    //data = data OR mask, set the specified bit to “1”
                }
                else {
                    data &= ~(uint)bit;
                    //data = data AND ~mask, set the specified bit to “0”
                }
            }
    }
     
    

    当然,你可以把it当成mask,这样就很容易理解了。

    【讨论】:

    • 很好的解释。坦率地说,MSFT 的文档有点迟钝——他们本可以做得更好,因为这并不是很明显。现在很高兴知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多