close

The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false.

條件運算子?:(也稱為三元條件運算子)計算布林運算式並返回兩個運算式之一的結果,具體取決於布林運算式是計算到true還是false

條件運算子的語法如下:

                     condition ? consequent : alternative 

condition 運算式必須評估為 truefalse 如果 condition 評估為 true,則會接著評估 consequent 運算式,且其結果會成為運算的結果。 如果 condition 評估為 false,則會接著評估 alternative 運算式,且其結果會成為運算的結果。 系統只會評估 consequentalternative

consequentalternative 的型別必須相同,或是必須有從一個型別轉換成另一型別的隱含轉換。

ref: https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/conditional-operator

但今天無意中在組合字串時犯了一個錯誤

image

str2 本以為會是 測試str3測試2 或  測試null測試2

但結果是 

image

"測試" + str1 == null ? "null" : str3 + "測試2"; 

這樣寫 把 "測試" + str1 當成 條件了 

image

image

arrow
arrow
    文章標籤
    C#
    全站熱搜

    JosephChou 發表在 痞客邦 留言(0) 人氣()


    留言列表 留言列表

    發表留言