跳至頁尾內容
Iron Academy Logo
學習C#
學習C#

其他類別

C#空值條件運算符

[{academy-video-youtube({"vid": "eOpmjGF4qxo", "start_time": "0", "title": "C# Null-Conditional Operator (? 運算子) 解釋!

在他的影片之一中,Gerald Versluis 遇到了關於他範例程式碼中問號 (?) 的問題。 這促使他建立了一段詳細的影片來解釋C# 中的空條件運算子。 如果您曾經想知道?[ ]在 C# 中的作用,Gerald 的影片是一個很好的資源,可讓您清楚理解這一點。 讓我們一步步地跟進他的解釋。

通過檔案頁面的快速解釋

Gerald 首先參考了微軟官方檔案中的成員存取運算符和表達式。 他突出介紹了在 C# 6 引入的空條件運算符部分。在錄製時,最新版本為 C# 9,而 C# 10 即將到來。

Gerald 說明當您使用a為空,整個表達式會計算為空而不是丟擲空引用異常。 否則,將正常檢索值。

雖然文件很有幫助,但 Gerald 更喜歡實作範例,所以他轉向互動的編碼環境。

通過 try.dot.net 的範例

為了演示,Gerald 切換到 try.dot.net,一個互動的 C#環境。 他提到這個工具運行在 Blazor 上,允許使用者直接在瀏覽器中執行 C#程式碼。

他簡要展示了 try.dot.net 中預載的預設斐波那契數列範例,然後清除它以開始集中於空條件運算子的新的範例。

空條件運算子解釋

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);

運行此程式碼會引發空引用例外,因為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 解釋了空條件運算子如何簡化這一過程:

// 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為空,表達式只會返回空值而不會當機。

屬性上的空條件運算子

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 條件。

鏈式空條件運算子

Gerald 解釋了空條件運算子可以被連結使用,當處理深層巢狀的物件時,使程式碼更加清晰。 您可以使用以下方式代替編寫多個空檢查:

// 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.Partner,結果將為,從而防止運行時錯誤。

陣列上的空條件運算子

Gerald 將討論延伸至陣列和集合。 他在 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]);

如果Hobbies,則表達式會評估為而不是引發例外。

結論

Gerald 的影片深入探討了 C# 中的空條件運算子。 通過使用?[ ],開發者可以編寫更簡潔、更安全的程式碼,避免空引用異常。 不論是處理屬性、巢狀物件或陣列,空條件運算子使程式碼更簡潔且更易讀。

欲進一步了解完整演示,請務必查看Gerald Versluis 的影片,在其中他以實作範例解釋一切!

Hero Worlddot related to C#空值條件運算符
Hero Affiliate related to C#空值條件運算符

分享您所愛以賺取更多報酬

您是否為使用 .NET、C#、Java、Python 或 Node.js 的開發者建立內容?將您的專業知識轉化為額外收入!

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話