C# else if 语句
else if 语句
如果第一个条件为False
,则使用else if
语句指定一个新条件。
语法
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
示例
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
// Outputs "Good evening."
示例说明
在上面的示例中,时间(22)大于 10,因此第一个条件为False
。 else if
语句中的下一个条件也为False
,因此我们移至else
条件,因为condition1和condition2都为False
——并在屏幕上打印“晚上好”。
但是,如果时间是 14,我们的程序将打印 "Good day."