溫馨提示×

如何在C#中優(yōu)雅地處理Optional鏈

c#
小樊
81
2024-09-08 04:24:13
欄目: 編程語言

在 C# 9.0 及以上版本中,可以使用 null 聚合運算符(?.)來優(yōu)雅地處理 Optional 鏈

public class Address
{
    public string? City { get; set; }
}

public class Person
{
    public Address? Address { get; set; }
}

public class Program
{
    public static void Main()
    {
        Person? person = GetPerson(); // 假設這個方法可能返回 null

        string? cityName = person?.Address?.City;
        
        if (cityName != null)
        {
            Console.WriteLine($"City: {cityName}");
        }
        else
        {
            Console.WriteLine("City information not available.");
        }
    }

    private static Person? GetPerson()
    {
        // 實現(xiàn)獲取 Person 對象的邏輯,可能返回 null
        return new Person { Address = new Address { City = "New York" } };
    }
}

在這個示例中,我們使用了 null 聚合運算符(?.)來優(yōu)雅地處理 Optional 鏈。當 personAddressCity 為 null 時,整個表達式將返回 null。否則,它將返回城市名稱。通過這種方式,我們可以避免在代碼中顯式檢查每個屬性是否為 null。

0