if-else (C# 參考)if-else (C# Reference)

if 陳述式會根據布林運算式的值識別要執行的陳述式。An if statement identifies which statement to run based on the value of a Boolean expression. 在下列範例中, bool 變數 condition 設為 true ,然後以 if 陳述式進行檢查。In the following example, the bool variable condition is set to true and then checked in the if statement. 輸出為 The variable is set to true.The output is The variable is set to true..

bool condition = true;

if (condition)
{
    Console.WriteLine("The variable is set to true.");
}
else
{
    Console.WriteLine("The variable is set to false.");
}

您也可以將本主題中的範例放在主控台 App 的 Main 方法執行。You can run the examples in this topic by placing them in the Main method of a console app.

如下列範例所示, if 陳述式在 C# 中可能有兩種形式。An if statement in C# can take two forms, as the following example shows.

// if-else statement
if (condition)
{
    then-statement;
}
else
{
    else-statement;
}
// Next statement in the program.

// if statement without an else
if (condition)
{
    then-statement;
}
// Next statement in the program.

if-else 陳述式中,如果 condition 評估為 true,則執行 then-statementIn an if-else statement, if condition evaluates to true, the then-statement runs. 如果 condition 為 false,則執行 else-statementIf condition is false, the else-statement runs. 由於 condition 無法同時為 true 和 false,所以 then-statement 陳述式的 else-statementif-else 永遠無法同時執行。Because condition can’t be simultaneously true and false, the then-statement and the else-statement of an if-else statement can never both run. 在執行 then-statementelse-statement 後,控制權會轉移到在 if 陳述式之後的下一個陳述式。After the then-statement or the else-statement runs, control is transferred to the next statement after the if statement.

在不包含 if 陳述式的 else 陳述式,如果 condition 為 true,則執行 then-statementIn an if statement that doesn’t include an else statement, if condition is true, the then-statement runs. 如果 condition 為 false,控制權會轉移到在 if 陳述式之後的下一個陳述式。If condition is false, control is transferred to the next statement after the if statement.

then-statementelse-statement 皆可包含以大括弧括住 ({}) 的單一陳述式或多個陳述式。Both the then-statement and the else-statement can consist of a single statement or multiple statements that are enclosed in braces ({}). 對於單一陳述式,大括弧是選擇項,但建議使用。For a single statement, the braces are optional but recommended.

then-statementelse-statement 的陳述式可以是任何類型,包括其他在原始 if 陳述式內巢狀的 if 陳述式。The statement or statements in the then-statement and the else-statement can be of any kind, including another if statement nested inside the original if statement. 在巢狀 if 陳述式,每個 else 子句都隸屬於最後一個沒有相對應 ifelseIn nested if statements, each else clause belongs to the last if that doesn’t have a corresponding else. 在下列範例中,如果 Result1m > 10 都評估為 true,則會顯示 n > 20In the following example, Result1 appears if both m > 10 and n > 20 evaluate to true. 如果 m > 10 為 true,但 n > 20 是 false,則會顯示 Result2If m > 10 is true but n > 20 is false, Result2 appears.

// Try with m = 12 and then with m = 8.
int m = 12;
int n = 18;

if (m > 10)
    if (n > 20)
    {
        Console.WriteLine("Result1");
    }
    else
    {
        Console.WriteLine("Result2");
    }

如果相反地,您希望 Result2(m > 10) 為 false 時顯示,則可以使用大括弧指定關聯,以建立巢狀 if 陳述式的開頭和結尾,如下列範例所示。If, instead, you want Result2 to appear when (m > 10) is false, you can specify that association by using braces to establish the start and end of the nested if statement, as the following example shows.

// Try with m = 12 and then with m = 8.
if (m > 10)
{
    if (n > 20)
        Console.WriteLine("Result1");
}
else
{
    Console.WriteLine("Result2");
}

如果條件Result2 評估為 false,就會顯示 (m > 10)Result2 appears if the condition (m > 10) evaluates to false.

範例Example

在下列範例中,將由鍵盤輸入字元,而程式會使用巢狀 if 陳述式判斷輸入字元是否為字母字元。In the following example, you enter a character from the keyboard, and the program uses a nested if statement to determine whether the input character is an alphabetic character. 如果輸入字元是字母字元,程式就會檢查輸入的字元是大寫或小寫,If the input character is an alphabetic character, the program checks whether the input character is lowercase or uppercase. 並顯示每一種情況的訊息。A message appears for each case.

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("The character isn't an alphabetic character.");
}

//Sample Output:

//Enter a character: 2
//The character isn't an alphabetic character.

//Enter a character: A
//The character is uppercase.

//Enter a character: h
//The character is lowercase.

範例Example

也可以將if語句嵌套在 else 塊中,如下部分代碼所示。You can also nest an if statement inside an else block, as the following partial code shows. 此範例將 if 以巢狀方式置於兩個 else 區塊和一個 then 區塊內部。The example nests if statements inside two else blocks and one then block. 在每個區塊中,註解指定哪些條件為 true 或 false。The comments specify which conditions are true or false in each block.

// Change the values of these variables to test the results.
bool Condition1 = true;
bool Condition2 = true;
bool Condition3 = true;
bool Condition4 = true;

if (Condition1)
{
    // Condition1 is true.
}
else if (Condition2)
{
    // Condition1 is false and Condition2 is true.
}
else if (Condition3)
{
    if (Condition4)
    {
        // Condition1 and Condition2 are false. Condition3 and Condition4 are true.
    }
    else
    {
        // Condition1, Condition2, and Condition4 are false. Condition3 is true.
    }
}
else
{
    // Condition1, Condition2, and Condition3 are false.
}

範例Example

下列範例會判斷輸入字元是否為小寫字母、大寫字母或數字。The following example determines whether an input character is a lowercase letter, an uppercase letter, or a number. 如果這三個條件為 false,字元不是英數字元。If all three conditions are false, the character isn’t an alphanumeric character. 這個範例會顯示每一種情況的訊息。The example displays a message for each case.

Console.Write("Enter a character: ");
char ch = (char)Console.Read();

if (Char.IsUpper(ch))
{
    Console.WriteLine("The character is an uppercase letter.");
}
else if (Char.IsLower(ch))
{
    Console.WriteLine("The character is a lowercase letter.");
}
else if (Char.IsDigit(ch))
{
    Console.WriteLine("The character is a number.");
}
else
{
    Console.WriteLine("The character is not alphanumeric.");
}

//Sample Input and Output:
//Enter a character: E
//The character is an uppercase letter.

//Enter a character: e
//The character is a lowercase letter.

//Enter a character: 4
//The character is a number.

//Enter a character: =
//The character is not alphanumeric.

就像在 else 區塊或 then 區塊中的陳述式可以是任何有效的陳述式一樣,您可以為這個條件使用任何有效的布林運算式。Just as a statement in the else block or the then block can be any valid statement, you can use any valid Boolean expression for the condition. 可以使用邏輯運算符(!``&&&``|``^``||、、、、 和 )來制定複合條件。You can use logical operators such as !, &&, ||, &, |, and ^ to make compound conditions. 下列程式碼顯示範例。The following code shows examples.

// NOT
bool result = true;
if (!result)
{
    Console.WriteLine("The condition is true (result is false).");
}
else
{
    Console.WriteLine("The condition is false (result is true).");
}

// Short-circuit AND
int m = 9;
int n = 7;
int p = 5;
if (m >= n && m >= p)
{
    Console.WriteLine("Nothing is larger than m.");
}

// AND and NOT
if (m >= n && !(p > m))
{
    Console.WriteLine("Nothing is larger than m.");
}

// Short-circuit OR
if (m > n || m > p)
{
    Console.WriteLine("m isn't the smallest.");
}

// NOT and OR
m = 4;
if (!(m >= n || m >= p))
{
    Console.WriteLine("Now m is the smallest.");
}
// Output:
// The condition is false (result is true).
// Nothing is larger than m.
// Nothing is larger than m.
// m isn't the smallest.
// Now m is the smallest.

C# 語言規格C# language specification

如需詳細資訊,請參閱c # 語言規格For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also