为什么.NET可选System.Boolean需要4个字节?

编程入门 行业动态 更新时间:2024-10-05 23:28:53
本文介绍了为什么.NET可选System.Boolean需要4个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么可选System.Boolean需要4个字节,即使它只是存储一个状态TRUE或FALSE;其可以存储少于4字节?

Why System.Boolean takes 4 bytes even if it just stores one state TRUE or FALSE; which may be stored less than 4 bytes?

推荐答案

A 布尔实际上只有1个字节,但调整可能会导致在32使用的4个字节比特平台,或者甚至8个字节在64位的平台上。例如,可空<布尔> (?又名布尔)的类型采用了全32位或64位,这取决于平台,即使它仅仅由两个布尔取值。 修改:正如乔恩飞碟双向,填充对准不是的总是的present。举个例子,数组可空<布尔> S可每个对象,而不是4只2个字节或8

A bool is actually only 1 byte, but alignment may cause 4 bytes to be used on a 32-bit platform, or even 8 bytes on a 64-bit platform. For example, the Nullable<bool> (aka bool?) type uses a full 32 or 64 bits—depending on platform—even though it's comprised of just two bools. EDIT: As pointed out by Jon Skeet, padding for alignment isn't always present. As an example, an array of Nullable<bool>s takes only 2 bytes per object instead of 4 or 8.

不过,即使8位,重新present一个布尔可以被认为是一种浪费,如果你有很多人到店里。出于这个原因,如果你创建具有许多布尔取值为成员(或使用许多类型可空&LT;&GT; 类型),和用户类可能会创建它的很多情况下,你可能会考虑使用 BitVector32 代替。该框架本身使用该技术,以减少许多的Windows的内存占用窗体控件,例如。

But even 8 bits to represent a bool can be considered wasteful if you have many of them to store. For this reason, if you create a type that has many bools as members, (or uses many Nullable<> types), and users of your class might create many instances of it, you might consider using a BitVector32 instead. The framework itself uses this technique to reduce the memory footprint of many of the Windows Forms controls, for instance.

更多推荐

为什么.NET可选System.Boolean需要4个字节?

本文发布于:2023-11-03 04:07:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554201.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   字节   NET   Boolean   System

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!