C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).
Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.
在第 312 页介绍了 BitArrays 作为 .NET 提供的集合类型之一:
BitArray
A BitArray is a dynamically sized collection of compacted bool values. It is more memory-efficient than both a simple array of bool and a generic List of bool, because it uses only one bit for each value, whereas the bool type otherwise occupies one byte for each value.
当您只对二进制值感兴趣时,很高兴能够声明一个位集合而不是处理字节,但是声明一个位字段呢?
喜欢:
public class X
{
public [bit-type] MyBit {get; set;}
}
.NET 不支持吗?
涉及该主题的现有帖子讨论了在字节变量中设置各个位。我想问的是,一旦 .NET 考虑支持在集合中使用位变量,它是否也支持声明非集合这样的变量。
最佳答案
所以你的问题是 .NET 是否支持这个。答案是否定的。
为什么?具有这样的特性是根本上可能的。但是需求真的很低。最好将开发人员的时间投入到其他地方。
如果你想使用低于字节粒度的内存,你需要自己构建它。 BitArray
不是运行时固有的。它操纵一些更大类型的位(我认为它是基于 int
的)。您可以做同样的事情。
BitVector32
是一个内置结构,您可以使用它来单独寻址 32 位。
关于c# - 在 C# 中将字段声明为位(作为单个位,而不是字节倍数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746160/