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#中的原始布尔大小


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01