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#中的原始布尔大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#中的原始布尔大小


- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01