C# 中的空條件操作符
[{academy-video-youtube({"vid": "eOpmjGF4qxo", "start_time": "0", "title": "C# Null-Conditional Operator (? )}] 運算子) 解釋!", "創建者": "Gerald Versluis", "長度": "13m 26s"})}
在他的一個影片中,Gerald Versluis 遇到一個關於他範例代碼中的問號(?)的問題。 這促使他創建了一個詳細的影片,解釋C# 中的 null-conditional 運算子。 如果您曾經想知道 ?. 或 ?[ ] 在 C# 中做了什麼,Gerald 的視頻是一個幫助您清楚了解的極好資源。 讓我們逐步了解他的解釋。
透過檔案頁面快速解釋
Gerald 剛開始提及官方 Microsoft 文檔中關於成員訪問運算子和表達式的說明。 他強調了關於 null-conditional 運算子的部分,此運算子是在 C# 6 中引入的。在錄製時,C# 9 是最新的版本,而 C# 10 即將到來。
Gerald 解釋說當您使用 a?.x 或 a?[index] 時,如果 a 是空值,整個表達式將評估為空值,而不是拋出 NullReferenceException。 否則,將正常檢索值。
雖然文檔是有幫助的,Gerald 更喜歡實際操作的范例,因此他轉到互動式編程環境。
透過 try.dot.net 的範例
為了示範,Gerald 轉到 try.dot.net,一個互動的 C# 環境。 他提到這個工具運行在 Blazor 上,允許用戶直接在瀏覽器中執行 C# 代碼。
他簡單地展示了預載在 try.dot.net 中的默認 Fibonacci 序列範例,然後清除它以開始一個新的示例,專注於 null-conditional 運算子。
解釋 null-conditional 運算子
Gerald 創建了一個簡單的 Person 類,具有以下屬性:
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}
他將 Person 對象初始化為空值:
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);
運行此代碼拋出了一個 NullReferenceException,因為 person 為空值。 為了防止這種情況,開發人員通常在訪問屬性前加入空值檢查:
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}
雖然這樣做有效,但它增加了額外的代碼行數。 Gerald 解釋了如何使用 null-conditional 運算子簡化此操作:
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);
現在,如果 person 為空值,該表達式將簡單地返回空值,而不會崩潰。
在屬性上使用 null-conditional 運算子
Gerald 擴展了這個例如,設置一個 Person 對象:
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);
由於 person 非空,它正確地打印"Gerald"。
接下來,他展示了一個嵌套的範例:
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);
如果 person.Partner 為空值,整個表達式評估為 空值,而不是拋出異常。 這樣可以避免不必要的 if 條件。
鏈接 null-conditional 運算子
Gerald 解釋說 null-conditional 運算子可以鏈式使用,在處理深度嵌套對象時使代碼更加簡潔。 而不是編寫多個空值檢查,您可以使用:
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);
如果 person 或 person.Partner 為空值,則結果將為 空值,從而防止運行時錯誤。
在陣列上使用 null-conditional 運算子
Gerald 將討論擴展到<array 和集合。 他在 Person 類中添加了一個 Hobbies 陣列,並展示如何安全地訪問元素:
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);
在這裡,如果 person 或 Hobbies 是 空值,表達式將評估為 空值,而不是引起異常。
結論
Gerald 的視頻深入解析了 C# 中的 null-conditional 運算子。 通過使用 ?. 和 ?[ ],開發人員可以編寫更乾淨、安全的代碼,避免 NullReferenceException。 無論是在處理屬性、嵌套對象還是陣列,null-conditional 運算子使代碼更加簡潔和易讀。
要進行完整演示,請務必查看Gerald Versluis 的視頻,他用實際範例解釋了一切!
