对SimpleBitVector32结构的理解
前段时间通过Reflector查看.net框架类,偶尔发现了SimpleBitVector32结构,在blog里也发现了对它的解释,
不过我感觉不太清晰,所以有必要再说明一下.其定义代码如下:
1 internal struct SimpleBitVector32
2 {
3 private int data;
4 internal SimpleBitVector32(int data)
5 {
6 this.data = data;
7 }
8 internal bool this[int bit]
9 {
10 get
11 {
12 return ((this.data & bit) == bit);
13 }
14 set
15 {
16 if (value)
17 {
18 this.data |= bit;
19 }
20 else
21 {
22 this.data &= ~bit;
23 }
24 }
25
26 }
27 internal int Data
28 { get
29 {
30 return this.data;
31 }
32 }
33 }
2 {
3 private int data;
4 internal SimpleBitVector32(int data)
5 {
6 this.data = data;
7 }
8 internal bool this[int bit]
9 {
10 get
11 {
12 return ((this.data & bit) == bit);
13 }
14 set
15 {
16 if (value)
17 {
18 this.data |= bit;
19 }
20 else
21 {
22 this.data &= ~bit;
23 }
24 }
25
26 }
27 internal int Data
28 { get
29 {
30 return this.data;
31 }
32 }
33 }
有人要问了,它有什么作用呢?说白了,它相当于一个逻辑数据,bool []长度为32(int 的长度),使用情形如下
1 private SimpleBitVector32 sb=new SimpleBitVector32(0);
2 sb[0x80]=true;
3 sb[0x40]=false;
4 if (sb[0x40])
5 {
6 Console.Write("第7位为1");
7 }
8 else
9 {
10 Console.Write("第7位为0");
11 }
12
2 sb[0x80]=true;
3 sb[0x40]=false;
4 if (sb[0x40])
5 {
6 Console.Write("第7位为1");
7 }
8 else
9 {
10 Console.Write("第7位为0");
11 }
12
第1行代码结构中的data用二进制表示为0000……0,32位都为0
其中第3行代码把第7位置为0,那么sb[0x40]肯定为false,
很明显输出:第7位为0