通过分支和循环语句了解条件逻辑

让 if 和 else 完美配合

若要执行 true 和 false 分支中的不同代码,请创建在条件为 false 时执行的 else 分支。 试运行以下代码:

C#
int a = 5;
int b = 3;
if (a + b > 10)
    Console.WriteLine("The answer is greater than 10");
else
    Console.WriteLine("The answer is not greater than 10");

只有当条件的测试结果为 false 时,才执行 else 关键字后面的语句。 将 ifelse 与布尔条件相结合,可以实现所需的一切目标。

重要

ifelse 语句下的缩进是为了方便读者阅读。 C# 语言忽略缩进或空格。 ifelse 关键字后面的语句根据条件决定是否执行。 本教程中的所有示例都遵循了常见做法,根据语句的控制流缩进代码行。

由于缩进会被忽略,因此需要使用 {} 指明何时要在根据条件决定是否执行的代码块中添加多个语句。 C# 程序员通常会对所有 ifelse 子句使用这些大括号。 以下示例与创建的示例相同。 试运行看看。

C#
int a = 5;
int b = 3;
if (a + b > 10)
{
    Console.WriteLine("The answer is greater than 10");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
}

提示

在本教程的其余部分中,代码示例全都遵循公认做法,添加了大括号。

可以测试更复杂的条件:

C#
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) && (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("And the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("Or the first number is not equal to the second");
}

== 符号执行相等测试。 使用 == 将相等测试与赋值测试区分开来,如在 a = 5 中所见。

&& 表示“且”。 也就是说,两个条件必须都为 true,才能执行 true 分支中的语句。 这些示例还表明,可以在每个条件分支中添加多个语句,前提是将它们用 {} 括住。

还可以使用 || 表示“或”:

C#
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) || (a == b))
{
    Console.WriteLine("The answer is greater than 10");
    Console.WriteLine("Or the first number is equal to the second");
}
else
{
    Console.WriteLine("The answer is not greater than 10");
    Console.WriteLine("And the first number is not equal to the second");
}

修改 abc 的值,并在 &&|| 之间切换浏览。 你将进一步了解 &&|| 运算符的工作原理。

在浏览器中尝试运行代码