C# มีโอเปอเรเตอร์สามตัวต่อไปนี้เพื่อจัดการกับค่า null -
ตัวดำเนินการการรวมค่า null (??)
ช่วยให้คุณได้รับค่าของตัวแปรหากไม่ใช่ค่าว่าง หรือระบุค่าเริ่มต้นที่สามารถใช้ได้
มันแทนที่นิพจน์ต่อไปนี้ใน 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
}
} ตัวดำเนินการกำหนดการรวมค่าว่าง (??=)
ส่งคืนค่าทางด้านซ้ายถ้าไม่เป็นค่าว่าง มิฉะนั้นจะส่งกลับค่าทางด้านขวา กล่าวอีกนัยหนึ่ง ช่วยให้คุณสามารถเริ่มต้นตัวแปรเป็นค่าเริ่มต้นได้หากค่าปัจจุบันเป็นโมฆะ
มันแทนที่นิพจน์ต่อไปนี้ใน 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 (?.)
โอเปอเรเตอร์นี้อนุญาตให้คุณเรียกใช้เมธอดบนอินสแตนซ์ได้อย่างปลอดภัย หากอินสแตนซ์เป็น null จะส่งกลับค่า 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