C# 提供哪些運算子來處理空值?


C# 有以下三個運算子用於處理空值:

空合併運算子 (??)

允許你在變數不為空時獲取其值,或者指定一個可用的預設值。

它替換了 C# 中的以下表達式:

string resultOne = value != null ? value : "default_value";

為以下表達式:

string resultTwo = value ?? "default_value";

以下是一個示例。

示例

using System;
class Program{
   static void Main(){
      string input = null;
      string choice = input ?? "default_choice";
      Console.WriteLine(choice); // default_choice
      string finalChoice = choice ?? "not_chosen";
      Console.WriteLine(finalChoice); // default_choice
   }
}

空合併賦值運算子 (??=)

如果左側的值不為空,則返回左側的值;否則,返回右側的值。換句話說,它允許你將變數初始化為某個預設值,如果其當前值為 null。

它替換了 C# 中的以下表達式:

if (result == null)
result = "default_value";

為以下表達式。

result ??= "default_value";

此運算子對於延遲計算的屬性非常有用,例如:

示例

class Tax{
   private Report _lengthyReport;
   public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();
   private Report CalculateLengthyReport(){
      return new Report();
   }
}

空條件運算子 (?.)

此運算子允許你安全地呼叫例項上的方法。如果例項為空,則返回 null,而不是丟擲 NullReferenceException。否則,它只是簡單地呼叫該方法。

它替換了 C# 中的以下表達式:

string result = instance == null ? null : instance.Method();

為以下表達式:

string result = instance?.Method();

考慮以下示例。

示例

using System;
string input = null;
string result = input?.ToString();
Console.WriteLine(result); // prints nothing (null)

示例

 線上演示

using System;
class Program{
   static void Main(){
      string input = null;
      string choice = input ?? "default_choice";
      Console.WriteLine(choice); // default_choice
      string finalChoice = choice ?? "not_chosen";
      Console.WriteLine(finalChoice); // default_choice
      string foo = null;
      string answer = foo?.ToString();
      Console.WriteLine(answer); // prints nothing (null)
   }
}

輸出

default_choice
default_choice

更新於:2021年5月19日

344 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.