其实这个概念,很多同学还是有些模模糊糊滴~甚至Xushine研究院都见过很多同学在概念上混用滴说。。。

今天在这里来详细的解说下关于这些概念,不得不提到啊,Xushine研究院确实见过又把这两个概念的区分成为值类型和引用类型的。。。汗啊 ,如此的误人子弟,悲催~

那么bool与Boolean的区别是什么呢?其实他们最大的区别是bool只有4个字母并且都是小写,Boolean有7个字母并且首字母大写,所以确切地说,是:C# 中 bool 与 System.Boolean 没有区别, bool 是 System.Boolean 的别名。这个如何理解呢?

bool就像你的小名,你父母以及你们家的内部所属的成员都认识,但是Boolean就是你的大名了。大家都认识。不过不管按照大名还是小名称呼你,最终的目的是一样的,还是指的是你。

虽然MSDN也明确的表示了“The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false”,但是细究起来,C# 中 bool 与 Boolean 还是有一点区别的,那就是:
C# code//using System;//假设 using System; 被注释掉了classProgram
{staticvoidMain()
{boolisOK=false;//没问题Boolean isNotOK=true;//error CS0246: 找不到类型或命名空间名称“Boolean”(是否缺少 using 指令或程序集引用?)}
}

还有人说bool和Boolean还有一个区别就是执行速度的问题,其实这个担心是毫无疑义的,其实Xushine研究院建议大家可以自己用ILDASM看一下,因为编译生成的IL代码是一样,没有区别的。

假设有如下程序:

class Program
{
  void Method1()
  {
    bool a;
  }

  void Method2()
  {
    System.Boolean a;
  }

  static void Main(){}
}

编译一下,有两个警告,不用理会,

Program.cs(5,10): warning CS0168: 声明了变量“a”,但从未使用过
Program.cs(10,20): warning CS0168: 声明了变量“a”,但从未使用过

然后用 ILDASM 看一上生成的 Program.exe,我们会看到:

.method private hidebysig instance void  Method1() cil managed
{
  // 代码大小       2 (0x2)
  .maxstack  0
  .locals init (bool V_0)
  IL_0000:  nop
  IL_0001:  ret
} // end of method Program::Method1
.method private hidebysig instance void  Method2() cil managed
{
  // 代码大小       2 (0x2)
  .maxstack  0
  .locals init (bool V_0)
  IL_0000:  nop
  IL_0001:  ret
} // end of method Program::Method2