我现在正在调试一些代码(VS 2019,.NET Framework4.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
发布于 2020-09-28 09:54:03
实际上是,这个问题关系到对BitVector32[ ]索引的理解。
首先,stillInHand[1]并不意味着获得第二位stillInHand(BitVector32)。它表示此操作:使用00 00 … 00 01使用stillInHand(BitVector32)执行&(和)操作。
的例子是:stillInHand(BitVector32)是00 00 00 00 00 … 00 00 00 11 00,1是00 00 00 00 00 … 00 00 00 00 01。然后执行&(和)操作。
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,因此如果输出或看到stillInHand[1]的结果,结果将是false。
So,对于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。
实际上是,如果您从这里分析源代码:参考源,您可以看到以下代码:
/// <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,这将很容易理解。
https://stackoverflow.com/questions/64072807
复制相似问题