Boolean和bool VS. 鸡蛋和鸡

本文深入探讨了C#中Boolean类型的内部实现,包括其在内存中的占用情况,以及通过反汇编mscorlib.dll揭示的Boolean类型源代码。文章还讨论了Boolean与bool关键字之间的关系,以及Boolean类型如何实现IComparable、IConvertible等接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



    C/C++中没有提供bool类型,我们可以用0和非0取而代之;而在.Net中则提供了一个Boolean类型,其实是对0/1的一个封装。下面我们来看下这段代码:
Boolean b= true;
Console.WriteLine(
sizeof(Boolean));//得到的结果是1byte
unsafe//先要用/unsafe(项目属性->Build->Allow unsafe code)来关闭安全检查
...{
    
int i = (int)&b;//取地址
    Console.WriteLine(*(byte*)i);//上面得到bool类型占1byte,这里将Boolean中的值按byte来读取
}

    得出的结果是1,当Boolean变量b赋值为false时,得到的结果是0。虽然只用1个bit就可以表示0/1了,但计算机存储的最小单位是byte,没办法只好浪费另外7个bit了:)

 


    现在转入正题来扯淡,出于对Boolean的好奇,我用Reflector反汇编了下mscorlib.dll,得到Boolean的源代码(完整的代码见附录),居然看到了下面的内容:

    public struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool>
    
...{
        
private bool m_value;
        
//省略其他成员的定义.....
    }

    MSDN中解释bool与Boolean的关系是:“bool 关键字是 System.Boolean 的别名”。观察上面的Boolean类型定义,在其继承的泛型接口和成员变量中,我们找到了“bool”的影子(我想可能时Reflector将IL代码反汇编时将类型Boolean翻译成C#中的关键字bool),也就是说Boolean的定义依赖与bool(Boolean)。这就好比鸡蛋与鸡,到底是先有鸡蛋还是先有鸡?到底是先有Boolean的类型定义还是先有Boolean类型呢? 


附录 - Boolean类源码:

ContractedBlock.gifExpandedBlockStart.gif
  1None.gifnamespace System
  2ExpandedBlockStart.gifContractedBlock.gifdot.gif{
  3InBlock.gif    using System.Globalization;
  4InBlock.gif    using System.Runtime.InteropServices;
  5InBlock.gif
  6InBlock.gif    [Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
  7InBlock.gif    public struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool>
  8ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
  9InBlock.gif        internal const int True = 1;
 10InBlock.gif        internal const int False = 0;
 11InBlock.gif        internal const string TrueLiteral = "True";
 12InBlock.gif        internal const string FalseLiteral = "False";
 13InBlock.gif        private bool m_value;
 14InBlock.gif        private static char[] m_trimmableChars;
 15InBlock.gif        public static readonly string TrueString;
 16InBlock.gif        public static readonly string FalseString;
 17InBlock.gif        public override int GetHashCode()
 18ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 19InBlock.gif            if (!this)
 20ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 21InBlock.gif                return 0;
 22ExpandedSubBlockEnd.gif            }

 23InBlock.gif            return 1;
 24ExpandedSubBlockEnd.gif        }

 25InBlock.gif
 26InBlock.gif        public override string ToString()
 27ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 28InBlock.gif            if (!this)
 29ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 30InBlock.gif                return "False";
 31ExpandedSubBlockEnd.gif            }

 32InBlock.gif            return "True";
 33ExpandedSubBlockEnd.gif        }

 34InBlock.gif
 35InBlock.gif        public string ToString(IFormatProvider provider)
 36ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 37InBlock.gif            if (!this)
 38ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 39InBlock.gif                return "False";
 40ExpandedSubBlockEnd.gif            }

 41InBlock.gif            return "True";
 42ExpandedSubBlockEnd.gif        }

 43InBlock.gif
 44InBlock.gif        public override bool Equals(object obj)
 45ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 46InBlock.gif            if (obj is bool)
 47ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 48InBlock.gif                return (this == ((bool) obj));
 49ExpandedSubBlockEnd.gif            }

 50InBlock.gif            return false;
 51ExpandedSubBlockEnd.gif        }

 52InBlock.gif
 53InBlock.gif        public bool Equals(bool obj)
 54ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 55InBlock.gif            return (this == obj);
 56ExpandedSubBlockEnd.gif        }

 57InBlock.gif
 58InBlock.gif        public int CompareTo(object obj)
 59ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 60InBlock.gif            if (obj != null)
 61ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 62InBlock.gif                if (!(obj is bool))
 63ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 64InBlock.gif                    throw new ArgumentException(Environment.GetResourceString("Arg_MustBeBoolean"));
 65ExpandedSubBlockEnd.gif                }

 66InBlock.gif                if (this == ((bool) obj))
 67ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 68InBlock.gif                    return 0;
 69ExpandedSubBlockEnd.gif                }

 70InBlock.gif                if (!this)
 71ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 72InBlock.gif                    return -1;
 73ExpandedSubBlockEnd.gif                }

 74ExpandedSubBlockEnd.gif            }

 75InBlock.gif            return 1;
 76ExpandedSubBlockEnd.gif        }

 77InBlock.gif
 78InBlock.gif        public int CompareTo(bool value)
 79ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 80InBlock.gif            if (this == value)
 81ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 82InBlock.gif                return 0;
 83ExpandedSubBlockEnd.gif            }

 84InBlock.gif            if (!this)
 85ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 86InBlock.gif                return -1;
 87ExpandedSubBlockEnd.gif            }

 88InBlock.gif            return 1;
 89ExpandedSubBlockEnd.gif        }

 90InBlock.gif
 91InBlock.gif        public static bool Parse(string value)
 92ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 93InBlock.gif            if (value == null)
 94ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 95InBlock.gif                throw new ArgumentNullException("value");
 96ExpandedSubBlockEnd.gif            }

 97InBlock.gif            bool result = false;
 98InBlock.gif            if (!TryParse(value, out result))
 99ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
100InBlock.gif                throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
101ExpandedSubBlockEnd.gif            }

102InBlock.gif            return result;
103ExpandedSubBlockEnd.gif        }

104InBlock.gif
105InBlock.gif        public static bool TryParse(string value, out bool result)
106ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
107InBlock.gif            result = false;
108InBlock.gif            if (value != null)
109ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
110InBlock.gif                if ("True".Equals(value, StringComparison.OrdinalIgnoreCase))
111ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
112InBlock.gif                    result = true;
113InBlock.gif                    return true;
114ExpandedSubBlockEnd.gif                }

115InBlock.gif                if ("False".Equals(value, StringComparison.OrdinalIgnoreCase))
116ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
117InBlock.gif                    result = false;
118InBlock.gif                    return true;
119ExpandedSubBlockEnd.gif                }

120InBlock.gif                if (m_trimmableChars == null)
121ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
122InBlock.gif                    char[] destinationArray = new char[string.WhitespaceChars.Length + 1];
123InBlock.gif                    Array.Copy(string.WhitespaceChars, destinationArray, string.WhitespaceChars.Length);
124InBlock.gif                    destinationArray[destinationArray.Length - 1= '\0';
125InBlock.gif                    m_trimmableChars = destinationArray;
126ExpandedSubBlockEnd.gif                }

127InBlock.gif                value = value.Trim(m_trimmableChars);
128InBlock.gif                if ("True".Equals(value, StringComparison.OrdinalIgnoreCase))
129ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
130InBlock.gif                    result = true;
131InBlock.gif                    return true;
132ExpandedSubBlockEnd.gif                }

133InBlock.gif                if ("False".Equals(value, StringComparison.OrdinalIgnoreCase))
134ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
135InBlock.gif                    result = false;
136InBlock.gif                    return true;
137ExpandedSubBlockEnd.gif                }

138ExpandedSubBlockEnd.gif            }

139InBlock.gif            return false;
140ExpandedSubBlockEnd.gif        }

141InBlock.gif
142InBlock.gif        public TypeCode GetTypeCode()
143ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
144InBlock.gif            return TypeCode.Boolean;
145ExpandedSubBlockEnd.gif        }

146InBlock.gif
147InBlock.gif        bool IConvertible.ToBoolean(IFormatProvider provider)
148ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
149InBlock.gif            return this;
150ExpandedSubBlockEnd.gif        }

151InBlock.gif
152InBlock.gif        char IConvertible.ToChar(IFormatProvider provider)
153ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
154ExpandedSubBlockStart.gifContractedSubBlock.gif            throw new InvalidCastException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), new object[] dot.gif"Boolean""Char" }));
155ExpandedSubBlockEnd.gif        }

156InBlock.gif
157InBlock.gif        sbyte IConvertible.ToSByte(IFormatProvider provider)
158ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
159InBlock.gif            return Convert.ToSByte(this);
160ExpandedSubBlockEnd.gif        }

161InBlock.gif
162InBlock.gif        byte IConvertible.ToByte(IFormatProvider provider)
163ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
164InBlock.gif            return Convert.ToByte(this);
165ExpandedSubBlockEnd.gif        }

166InBlock.gif
167InBlock.gif        short IConvertible.ToInt16(IFormatProvider provider)
168ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
169InBlock.gif            return Convert.ToInt16(this);
170ExpandedSubBlockEnd.gif        }

171InBlock.gif
172InBlock.gif        ushort IConvertible.ToUInt16(IFormatProvider provider)
173ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
174InBlock.gif            return Convert.ToUInt16(this);
175ExpandedSubBlockEnd.gif        }

176InBlock.gif
177InBlock.gif        int IConvertible.ToInt32(IFormatProvider provider)
178ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
179InBlock.gif            return Convert.ToInt32(this);
180ExpandedSubBlockEnd.gif        }

181InBlock.gif
182InBlock.gif        uint IConvertible.ToUInt32(IFormatProvider provider)
183ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
184InBlock.gif            return Convert.ToUInt32(this);
185ExpandedSubBlockEnd.gif        }

186InBlock.gif
187InBlock.gif        long IConvertible.ToInt64(IFormatProvider provider)
188ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
189InBlock.gif            return Convert.ToInt64(this);
190ExpandedSubBlockEnd.gif        }

191InBlock.gif
192InBlock.gif        ulong IConvertible.ToUInt64(IFormatProvider provider)
193ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
194InBlock.gif            return Convert.ToUInt64(this);
195ExpandedSubBlockEnd.gif        }

196InBlock.gif
197InBlock.gif        float IConvertible.ToSingle(IFormatProvider provider)
198ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
199InBlock.gif            return Convert.ToSingle(this);
200ExpandedSubBlockEnd.gif        }

201InBlock.gif
202InBlock.gif        double IConvertible.ToDouble(IFormatProvider provider)
203ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
204InBlock.gif            return Convert.ToDouble(this);
205ExpandedSubBlockEnd.gif        }

206InBlock.gif
207InBlock.gif        decimal IConvertible.ToDecimal(IFormatProvider provider)
208ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
209InBlock.gif            return Convert.ToDecimal(this);
210ExpandedSubBlockEnd.gif        }

211InBlock.gif
212InBlock.gif        DateTime IConvertible.ToDateTime(IFormatProvider provider)
213ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
214ExpandedSubBlockStart.gifContractedSubBlock.gif            throw new InvalidCastException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("InvalidCast_FromTo"), new object[] dot.gif"Boolean""DateTime" }));
215ExpandedSubBlockEnd.gif        }

216InBlock.gif
217InBlock.gif        object IConvertible.ToType(Type type, IFormatProvider provider)
218ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
219InBlock.gif            return Convert.DefaultToType(this, type, provider);
220ExpandedSubBlockEnd.gif        }

221InBlock.gif
222InBlock.gif        static Boolean()
223ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
224InBlock.gif            TrueString = "True";
225InBlock.gif            FalseString = "False";
226ExpandedSubBlockEnd.gif        }

227ExpandedSubBlockEnd.gif    }

228ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/happyhippy/archive/2007/04/12/710928.html

<think>好的,我需要回答用户关于Java中booleanbool区别的问题。首先,根据用户提供的引用,我需要仔细查看每个引用的内容,确保信息准确。 引用[1]提到,C#boolboolean是同一类型,且是值类型。但用户的问题是Java,所以可能需要区分Java中的情况。不过引用[2]明确指出Java中的boolean是布尔类型,只能取true或false,不能使用0或1代替。这说明Java中boolean是基本数据类型。 然后引用[3]中的SQL语句使用了TRUEFALSE,可能与Java无关,但需要确认是否有其他语言的混淆。引用[4]讨论的是Swift中的Bool类型,与Java无关,但再次强调不同语言中的布尔类型可能有差异。 用户的问题核心是Java中的booleanbool。根据已知知识,Java的关键字是boolean,而bool并不是Java的关键字。可能用户混淆了其他语言如C#C++中的bool,在那些语言中bool是关键字,但在Java中不存在。需要明确说明这一点。 需要确认引用中是否有相关说明。引用[1]提到C#中的情况,但Java不同。引用[2][4]都提到Java使用boolean,而其他语言如Swift或C#使用不同名称。因此,结论是Java中只有boolean作为基本数据类型,没有bool类型。bool可能出现在其他上下文,比如变量名,但不是关键字。 此外,要指出boolean是值类型,而不是引用类型,这与引用[1]中提到的C#情况不同,但Java中的boolean确实是原始类型。需要确保回答准确,避免混淆不同语言的区别。 总结:Java中使用boolean作为布尔类型的关键字,没有bool类型。boolean是基本数据类型,只能取true或false,不能与int互换。而其他语言如C#C++使用bool,但Java不适用。</think>在Java语言中,布尔类型的使用规范与其他编程语言存在显著差异。以下是关于`boolean`与`bool`的对比分析: ### 1. **基本定义与语法差异** - **`boolean`**:是Java中唯一的布尔类型关键字,属于**基本数据类型(Primitive Type)**。其值只能是`true`或`false`,且严格区分大小写,不能以数字`0`或`1`替代[^2][^4]。 示例代码: ```java boolean isJava = true; boolean isCompiled = false; ``` - **`bool`**:在Java中**不存在**此关键字。某些语言如C#C++或Swift使用`bool`作为布尔类型关键字,但Java不支持这种写法[^1]。 ### 2. **类型特性** - **内存分配**:`boolean`作为基本类型,直接存储在栈内存中,占用空间较小(具体大小依赖JVM实现,通常为1字节)。 - **默认值**:未初始化的`boolean`变量默认值为`false`(类成员变量)或编译报错(局部变量需显式初始化)。 - **逻辑运算**:`boolean`类型支持逻辑运算符(`&&`、`||`、`!`),但**不能隐式转换为整数**,例如以下代码会报错: ```java int num = isJava; // 错误:不兼容的类型 ``` ### 3. **常见误区** - **与包装类的混淆**:Java提供`Boolean`类作为`boolean`的包装类,用于泛型或集合操作。例如: ```java Boolean wrapperBool = Boolean.TRUE; // 引用类型 ``` - **与其他语言的对比**:C#中`bool``Boolean`是同一类型的别名(均为值类型)[^1],而Java中`boolean`仅表示基本类型,`Boolean`是独立的引用类型。 ### 4. **应用场景** - 条件控制:`if`、`while`等语句的条件表达式必须为`boolean`类型。 - 标志位定义:用于程序逻辑的状态标记,例如开关控制、条件判断等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值