C# Else if 语句

使用 C# Else if 语句,我们可以比简单的 if 语句提高执行速度。这意味着当我们使用 Else if 控制流语句时,编译器将按顺序检查所有比较,直到给定的条件得到满足。一旦条件满足,它就会立即退出,而不会进行下一个比较。

Else if 语句语法

Else if 控制语句将克服简单 if 表达式的性能问题。这个 else if 语句的语法如下所示。

if <condition>
{
  Statements //These are executed if condition is true
}
else if <condition>
{
  Statements //These are executed when this else if condition is true
}
else if <condition>
{
  Statements //These sare executed when this else if condition is true
}
else
  <Default statements> //These are executed in case when neither of the above conditions is true. 

C# Else If 语句示例

让我们使用 else if 语句编写一个简单的示例。这与您在 if 条件中看到的示例相同。

这个例子读取从 1 到 4 的数字,并以文字形式打印出来。如果用户给出的数字不在 1 到 4 之间,则打印为无效数字。

using System;
class Program
{
    static void Main()
    {
        int i = int.Parse(Console.ReadLine());


        if (i == 1)
        {
            Console.WriteLine("input number is one");
        }
        else if (i == 2)
        {
            Console.WriteLine("input number is two");
        }
        else if (i == 3)
        {
            Console.WriteLine("input number is three");
        }
        else if (i == 4)
        {
            Console.WriteLine("input number is four");
        }
        else
        {
            Console.WriteLine("input number is invalid");
        }
    }
}
Else If Example

分析

这里 i = 2 作为用户输入。

首先,它检查 2==1,结果为 false。

在下一次迭代中,它检查 2==2 并返回 true。

因此它打印:输入数字是二。

然后它退出了循环,没有执行下一行。

分类 C#