bool 关键字是 System.Boolean 的别名。它用于声明变量来存储布尔值 true 和 false。
可将布尔值赋给 bool 变量。也可以将计算为 bool 类型的表达式赋给 bool 变量。
// keyword_bool.cs
using System;
public class MyClass
{
static void Main()
{
bool i = true;
char c = '0';
Console.WriteLine(i);
i = false;
Console.WriteLine(i);
bool Alphabetic = (c > 64 && c < 123);
Console.WriteLine(Alphabetic);
}
}
输出
在 C++ 中,bool 类型的值可转换为 int 类型的值;也就是说,false 等效于零值,而 true 等效于非零值。在 C# 中,不存在 bool 类型与其他类型之间的相互转换。例如,下列 if 语句在 C# 中是非法的,而在 C++ 中则是合法的:
int x = 123;
if (x) // Invalid in C#
{
printf_s("The value of x is nonzero.");
}
若要测试 int 类型的变量,必须将该变量与一个值(例如零)进行显式比较,如下所示:
int x = 123;
if (x != 0) // The C# way
{
Console.Write("The value of x is nonzero.");
}
在此例中,您从键盘输入一个字符,然后程序检查输入的字符是否是一个字母。如果输入的字符是字母,则程序检查是大写还是小写。这些检查是使用 IsLetter 和 IsLower(两者均返回 bool 类型)来执行的:
// keyword_bool_2.cs
using System;
public class BoolTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
}
}
输入
X
示例输出
Enter a character: X
The character is uppercase.
Additional sample runs might look as follow:
Enter a character: x
The character is lowercase.
Enter a character: 2
The character is not an alphabetic character.
有关 bool 和相关主题的更多信息,请参见 C# 语言规范 中的以下各节:
-
4.1.8 bool 类型
-
7.9.4 布尔相等运算符
-
7.11.1 布尔条件逻辑运算符
参考
C# 关键字
整型表(C# 参考)
内置类型表(C# 参考)
隐式数值转换表(C# 参考)
显式数值转换表(C# 参考)
概念
C# 编程指南
其他资源
C# 参考