close

condition ? first_expression : second_expression;  

condition 必須判斷值為 true 或 false。 如果 condition 為 true,則會評估 first_expression 並產生結果。 如果 condition 為 false,則會評估 second_expression 並產生結果。 只會評估兩個運算式的其中一個。
first_expression 和 second_expression 必須屬於相同類型,否則必須從其中一種類型隱含轉換為另一種類型。
你可以使用條件運算子更精確地表示可能需要 if-else 建構的計算。 例如,下列程式碼會先使用 if 陳述式,再使用條件運算子將整數分類為正數或負數。

int input = Convert.ToInt32(Console.ReadLine());
string classify;

// if-else construction.
if (input > 0)
classify = "positive";
else
classify = "negative";

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

arrow
arrow
    全站熱搜

    浩瀚宇宙超級無敵 發表在 痞客邦 留言(0) 人氣()