if 语句根据 Boolean 表达式的值选择要执行的语句。下面的示例将 Boolean 标志 flagCheck
设置为 true,然后在 if 语句中检查该标志。输出为:The flag is set to true
。
![]() | |
---|---|
bool flagCheck = true; if (flagCheck == true) { Console.WriteLine("The flag is set to true."); } else { Console.WriteLine("The flag is set to false."); } |
备注
如果括号里的表达式计算为 true,则执行 Console.WriteLine("The boolean flag is set to ture.");
语句。执行 if 语句之后,控制传递给下一个语句。在此例中不执行 else 语句。
如果想要执行的语句不止一个,可以通过使用 {} 将多个语句包含在块中,有条件地执行多个语句,如上例所示。
在测试条件时执行的语句可以是任何种类的,包括嵌套在原始 if 语句中的另一个 if 语句。在嵌套的 if 语句中,else 子句属于最后一个没有对应的 else 的 if。例如:
![]() | |
---|---|
if (x > 10) if (y > 20) Console.Write("Statement_1"); else Console.Write("Statement_2"); |
在此例中,如果条件 (y > 20)
计算为 false,将显示 Statement_2
。但如果要使 Statement_2
与条件 (x >10)
关联,则使用大括号:
![]() | |
---|---|
if (x > 10) { if (y > 20) Console.Write("Statement_1"); } else Console.Write("Statement_2"); |
在此例中,如果条件 (x > 10)
计算为 false,将显示 Statement_2
示例 1
说明
在此例中,您从键盘输入一个字符,而程序检查输入字符是否为字母字符。如果输入的字符是字母,则程序检查是大写还是小写。在任何一种情况下,都会显示适当的消息。
代码
![]() | |
---|---|
// statements_if_else.cs // if-else example using System; class IfTest { 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."); } } } |
输入
2 |
示例输出
Enter a character: 2 The character is not an alphabetic character. |
附加的示例可能如下所示:
运行示例 #2:
Enter a character: A The character is uppercase. |
运行示例 #3:
Enter a character: h The character is lowercase. |
还可以扩展 if 语句,使用下列 else-if 排列来处理多个条件:
if (Condition_1) { // Statement_1; } else if (Condition_2) { // Statement_2; } else if (Condition_3) { // Statement_3; } else { // Statement_n; } |
示例 2
说明
此示例检查输入字符是否是小写字符、大写字符或数字。否则,输入字符不是字母字符。程序利用 else-if 阶梯。
代码
![]() | |
---|---|
// statements_if_else2.cs // else-if using System; public class IfTest { static void Main() { Console.Write("Enter a character: "); char c = (char)Console.Read(); if (Char.IsUpper(c)) { Console.WriteLine("Character is uppercase."); } else if (Char.IsLower(c)) { Console.WriteLine("Character is lowercase."); } else if (Char.IsDigit(c)) { Console.WriteLine("Character is a number."); } else { Console.WriteLine("Character is not alphanumeric."); } } } |
输入
E |
示例输出
Enter a character: E The character is uppercase. |
附加的运行示例可能如下所示:
运行示例 #2:
Enter a character: e The character is lowercase. |
运行示例 #3:
Enter a character: 4 The character is a number. |
运行示例 #4:
Enter a character: $ The character is not alphanumeric. |
C# 语言规范
有关更多信息,请参见 C# 语言规范中的以下各章节:
-
5.3.3.5 If 语句
-
8.7.1 if 语句
请参见
