Primitive Boolean size in C#(C#中的原始布尔大小)
问题描述
C# 中的布尔变量如何存储在内存中?也就是说,它们是否存储为一个字节而其他 7 位被浪费了,或者在数组的情况下,它们是否被分组为 1 字节的布尔块?
How are boolean variables in C# stored in memory? That is, are they stored as a byte and the other 7 bits are wasted, or, in the case of arrays, are they grouped into 1-byte blocks of booleans?
这回答了关于 Java 的相同问题(为什么没有定义 Java 的布尔原始大小?一个>).Java 和 C# 在这方面是否相同?
This answers the same question regarding Java (Why is Java's boolean primitive size not defined?). Are Java and C# the same in this regard?
推荐答案
在 C# 中,当然 bits 默认不打包,因此多个 bool fields 将每个取 1 个字节.您可以使用 BitVector32
、BitArray
或简单的按位算术来减少这种开销.作为变量,我似乎记得它们占用 4 个字节(基本上处理为 int
= Int32
).
In C#, certainly the bits aren't packed by default, so multiple bool fields will each take 1 byte. You can use BitVector32
, BitArray
, or simply bitwise arithmetic to reduce this overhead. As variables I seem to recall they take 4 bytes (essentially handled as int
= Int32
).
例如,下面将 i
设置为 4:
For example, the following sets i
to 4:
struct Foo
{
public bool A, B, C, D;
}
static unsafe void Main()
{
int i = sizeof(Foo);
}
这篇关于C#中的原始布尔大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!