close

條件運算子 (?:) 是根據布林運算式的值傳回兩個值的其中一個。

以下是條件運算子的語法。

condition ? first_expression : second_expression; 

condition 必須判斷值為 truefalseThe condition must evaluate to true or false.

如果 conditiontrue,則會評估 first_expression 並產生結果。

 

string CompID = (Request["CompID"] != null) ? Request["CompID"].ToString() : "";
string UserID = (Request["UserID"] != null) ? Request["UserID"].ToString() : "";

 

If condition is true, first_expression is evaluated and becomes the result. 如果 conditionfalse

則會評估 second_expression 並產生結果。

If condition is false, second_expression is evaluated and becomes the result. 只會評估兩個運算式的其中一個。

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

 

條件運算子是右向關聯。

運算式 a ? b : c ? d : e 會判斷值為 a ? b : (c ? d : e),而不是 (a ? b : c) ? d : e

條件運算子不能多載。

 

class ConditionalOp
{
    static double sinc(double x) {
        return x != 0.0 ? Math.Sin(x) / x : 1.0;
    }

    static void Main() {
        Console.WriteLine(sinc(0.2));
        Console.WriteLine(sinc(0.1));
        Console.WriteLine(sinc(0.0));
    }
}
/* Output: 0.993346653975306 0.998334166468282 1 */
 

參考網址  https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/conditional-operator

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 可樂果公主 的頭像
    可樂果公主

    聽說幸福…在山的那邊 (浪機子)

    可樂果公主 發表在 痞客邦 留言(0) 人氣()