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."