值类型:bool
bool 关键字是 System.Boolean 的别名。它用于声明变量来存储布尔值 true 和 false。
![]() |
---|
如果需要一个也可以有 null 值的布尔型变量,请使用 bool?。有关更多信息,请参见 可空类型(C# 编程指南)。 |
本在线速查手册由www.w:3:x:u:e.com提供,请勿盗用!
文本
可将布尔值赋给 bool 变量。也可以将计算为 bool 类型的表达式赋给 bool 变量。
C# | |
---|---|
public class BoolTest { static void Main() { bool b = true; // WriteLine automatically converts the value of b to text. Console.WriteLine(b); int days = DateTime.Now.DayOfYear; // Assign the result of a boolean expression to b. b = (days % 2 == 0); if (true == b) { Console.WriteLine("days is an even number"); } else { Console.WriteLine("days is an odd number"); } } } /* Output: True days is an <even/odd> number */ |
本在线速查手册由www.w:3:x:u:e.com提供,请勿盗用!
转换
在 C++ 中,bool 类型的值可转换为 int 类型的值;也就是说,false 等效于零值,而 true 等效于非零值。在 C# 中,不存在 bool 类型与其他类型之间的相互转换。例如,下面的 if 语句在 C# 中无效:
C# | |
---|---|
int x = 123; // if (x) // Error: "Cannot implicitly convert type 'int' to 'bool'" { Console.Write("The value of x is nonzero."); } |
本在线速查手册由www.w:3:x:u:e.com提供,请勿盗用!
若要测试 int 类型的变量,必须将该变量与一个值(例如零)进行显式比较,如下所示:
C# | |
---|---|
if (x != 0) // The C# way { Console.Write("The value of x is nonzero."); } |
本在线速查手册由www.w:3:x:u:e.com提供,请勿盗用!
示例
在此例中,您从键盘输入一个字符,然后程序检查输入的字符是否是一个字母。如果字符是一个字母,则程序检查它是大写还是小写。这些检查是使用 IsLetter 和 IsLower(两者均返回 bool 类型)来执行的:
C# | |
---|---|
public class BoolKeyTest { 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."); } } } /* Sample Output: Enter a character: X The character is uppercase. Enter a character: x The character is lowercase. Enter a character: 2 The character is not an alphabetic character. */ |
本在线速查手册由www.w:3:x:u:e.com提供,请勿盗用!