为什么C#中没有一点结构?
值得一提的是,这里有一个完整的位结构,完整的int
和bool
铸造和算术运算.可能不完美,但对我来说效果很好.请享用!
////// Represents a single bit that can be implicitly cast to/from and compared /// with booleans and integers. /// ////// public struct Bit { ////// An instance with a value of one is equal to any non-zero integer and is true, /// an instance with a value of zero is equal to the integer zero and is false. /// ////// Arithmetic and logical AND, OR and NOT, as well as arithmetic XOR, are supported. /// ////// Creates a new instance with the specified value. /// /// public Bit(int value) : this() { Value = value == 0 ? 0 : 1; } ////// Gets the value of the bit, 0 or 1. /// public int Value { get; private set; } #region Implicit conversions public static implicit operator Bit(int value) { return new Bit(value); } public static implicit operator int(Bit value) { return value.Value; } public static implicit operator bool(Bit value) { return value.Value == 1; } public static implicit operator Bit(bool value) { return new Bit(value ? 1 : 0); } #endregion #region Arithmetic operators public static Bit operator |(Bit value1, Bit value2) { return value1.Value | value2.Value; } public static Bit operator &(Bit value1, Bit value2) { return value1.Value & value2.Value; } public static Bit operator ^(Bit value1, Bit value2) { return value1.Value ^ value2.Value; } public static Bit operator ~(Bit value) { return new Bit(value.Value ^ 1); } public static Bit operator !(Bit value) { return ~value; } #endregion #region The true and false operators public static bool operator true(Bit value) { return value.Value == 1; } public static bool operator false(Bit value) { return value.Value == 0; } #endregion #region Comparison operators public static bool operator ==(Bit bitValue, int intValue) { return (bitValue.Value == 0 && intValue == 0) || (bitValue.Value == 1 && intValue != 0); } public static bool operator !=(Bit bitValue, int intValue) { return !(bitValue == intValue); } public override bool Equals(object obj) { if(obj is int) return this == (int)obj; else return base.Equals(obj); } #endregion }
它被称为布尔值.至少,它会起到基本作用,对吧?你不会在C#中捏碎比特(至少,我没有),如果你需要,你可以使用内置的操作.
这里是一个BitArray类..
你想用它做什么?请记住,CLR不会尝试将多个变量打包到一个字节中,因此单独使用一个变量并不比布尔值更有用.如果你想拥有它们的集合 - 嗯,正如大卫指出的那样,这就是BitArray的用途.
如果我们确实有Bit结构,我怀疑人们会期望在内存中有效地打包多个Bit变量 - 由于首先没有类型,我们避免了这种期望并引导人们采用其他解决方案,如BitArray.