C# 无法解释此位向量32的状态
我现在正在调试一些代码(VS 2019,.NET Framework 4.7.2),在断点处停止,使用立即窗口来计算变量。我有一个C# 无法解释此位向量32的状态,c#,visual-studio,debugging,visual-studio-debugging,bitvector,C#,Visual Studio,Debugging,Visual Studio Debugging,Bitvector,我现在正在调试一些代码(VS 2019,.NET Framework 4.7.2),在断点处停止,使用立即窗口来计算变量。我有一个位向量32,我不了解它的状态。以下是IW的内容: stillInHand.ToString() "BitVector32{00000000000000000000000000001100}" stillInHand {BitVector32{00000000000000000000000000001100}} Data: 12 stillI
位向量32
,我不了解它的状态。以下是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不应该是真的
,其余的都是假的
?实际上,这个问题与理解位向量32[]
的索引有关
首先,stillInHand[1]
并不意味着获取stillInHand的第二位(BitVector32)。它表示此操作:使用00 00…00 01
执行&
(和)stillInHand(位向量32)操作
例如:stillInHand(BitVector32)
是00 00 00…00 00 11 00
,1
是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
因此,对于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
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
倒数第二位(关注索引值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 00 10 2
--------------------------------------------
00 00 00 00 00 … 00 00 00 00 00
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”
}
}
}
//
///获取或设置一个值,该值指示是否已设置所有指定位。
///
公共bool此[int位]{
得到{
返回(数据和位)==(uint)位;
//通过数据和掩码的AND操作清除其他位(至0)。
//如果操作结果等于掩码,则返回true。
//否则,返回false。
}
设置{
如果(值){
数据|=(uint)位;
//数据=数据或掩码,将指定位设置为“1”
}
否则{
数据&=~(uint)位;
//数据=数据和~掩码,将指定位设置为“0”
}
}
}
<强>当然<>强>,你可以考虑<代码>它<代码> > <代码>掩码< /代码>,这将是容易理解的。
伟大的解释。坦率地说,MSFT在这方面的文档有点迟钝——他们本可以做得更好,因为这不是很明显。很高兴现在知道!