C# 中的原始布尔大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2308034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Primitive Boolean size in C#
提问by
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?
C#中的布尔变量如何存储在内存中?也就是说,它们是否存储为一个字节而其他 7 位被浪费了,或者,在数组的情况下,它们是否被分组为 1 字节的布尔值块?
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?
这回答了关于 Java 的相同问题(为什么没有定义 Java 的布尔基元大小?)。Java 和 C# 在这方面是否相同?
回答by Stilgar
In C# they are stored as 1 byte in an array or a field but interestingly they are 4 bytes when they are local variables. I believe the 1-byteness of bool is defines somewhere in the .NET docs unlike Java. I suppose the reason for the 4 bytes for local variables are to avoid masking the bits when readng 32bits in a register. Still the sizeof operator shows 1 byte because this is the only relevant size and everything else is implementation detail.
在 C# 中,它们在数组或字段中存储为 1 个字节,但有趣的是,当它们是局部变量时,它们是 4 个字节。我相信 bool 的 1 字节是在 .NET 文档中的某个地方定义的,与 Java 不同。我想局部变量的 4 个字节的原因是为了避免在寄存器中读取 32 位时屏蔽这些位。sizeof 运算符仍然显示 1 个字节,因为这是唯一相关的大小,其他一切都是实现细节。
回答by Marc Gravell
In C#, certainly the bitsaren't packed by default, so multiple bool fieldswill each take 1 byte. You can use BitVector32
, BitArray
, or simply bitwise arithmetic to reduce this overhead. As variablesI seem to recall they take 4 bytes (essentially handled as int
= Int32
).
在 C# 中,当然默认情况下不会对位进行打包,因此多个 bool字段将每个占用 1 个字节。您可以使用BitVector32
、BitArray
或简单的按位算术来减少这种开销。作为变量,我似乎记得它们需要 4 个字节(基本上处理为int
= Int32
)。
For example, the following sets i
to 4:
例如,以下设置i
为 4:
struct Foo
{
public bool A, B, C, D;
}
static unsafe void Main()
{
int i = sizeof(Foo);
}