c# 各種問號語法 ?


分類

建立時間: 2023年5月7日 07:02
更新時間: 2023年9月14日 08:39

說明

我想最基本的你應該知道三元運算子 var a = true ? 1 : 2;,但還有另外幾個 ??, ??=, ?., ?[]。本篇將介紹這些語法。

?:

先從基本的開始說起

int age = 25;
string message;

if (age >= 18)
{
    message = "You are an adult.";
}
else
{
    message = "You are a minor.";
}
Console.WriteLine(message);

這是一段檢查是否成年的判斷式,使用三元運算式後就可以簡化如下

int age = 25;
string message = age >= 18 ? "You are an adult." : "You are a minor.";
Console.WriteLine(message);

?? 和 ??=

這兩個之前在 深入淺出 C# 4/e 第11章 物件之死 心得分享 曾提到過。

??

null 聯合運算子 ??,檢查如果值是 null 就回傳替代值

Program.cs

using (var stringReader = new StringReader(""))
{
    // 當 nextLine 是 null 時,指派空字串給它
    var nextLine = stringReader.ReadLine() ?? String.Empty;
    Console.WriteLine("Line length is: {0}", nextLine.Length);
}

??=

看起來有點類似 +=,但實際用途同上,當值是 null 時就指派值給變數、屬性或欄位

Program.cs

using (var stringReader = new StringReader(""))
{
    var nextLine = stringReader.ReadLine();
    // 當 nextLine 是 null 時,指派空字串給它
    nextLine ??= "";
    Console.WriteLine("Line length is: {0}", nextLine.Length);
}

?. 和 ?[]

這兩個是 Null 條件運算子,主要是為了避免存取屬性和陣列索引遇到 null 導致發生 null 例外,詳細可參考 Null-conditional operators ?. and ?[]

  • 如果 a 的計算結果為 null ,則 a?[x]a?.x 的結果為 null
  • 如果 a 的計算結果為非 null,則 a?[x]a?.x 的結果會分別與 a[x]a.x 的結果相同。

以下擷取 Null-conditional operators ?. and ?[] 的範例

double SumNumbers(List<double[]> setsOfNumbers, int indexOfSetToSum)
{
    return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN;
}

var sum1 = SumNumbers(null, 0);
Console.WriteLine(sum1);  // output: NaN

var numberSets = new List<double[]>
{
    new[] { 1.0, 2.0, 3.0 },
    null
};

var sum2 = SumNumbers(numberSets, 0);
Console.WriteLine(sum2);  // output: 6

var sum3 = SumNumbers(numberSets, 1);
Console.WriteLine(sum3);  // output: NaN

主要看 return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? double.NaN; 這行。

  • 這行程式會先檢查 setsOfNumbers 是不是 null
  • 如果不是 null,再接著檢查 setsOfNumbers[indexOfSetToSum] 是不是 null
  • 如果不是 null,就會得到 setsOfNumbers[indexOfSetToSum].Sum() 的值。
  • 如果前面任何一個情況檢查到是null,整段 setsOfNumbers?[indexOfSetToSum]?.Sum() 就是 null
  • setsOfNumbers?[indexOfSetToSum]?.Sum()null 時,這行程式就會執行 return double.NaN;

備註:List<double[]> 就是可以存取好幾組 double 陣列的串列。

var numberSets = new List<double[]>
{
    new[] { 1.0, 2.0, 3.0 },
    null
};

如上,第1組 double[]new[] { 1.0, 2.0, 3.0 },第2組 double[]null

觀看次數: 932
?c#????=?.?:?[]conditionconditionalnulloperatoroperatorsternary三元運算子
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!