只需空检查+属性访问

问题描述 投票:1回答:1

是否有运算符在C#中简化此操作以避免空指针异常?

obj == null ? null : obj.Property;

就像是

obj?.Property;

我真的想摆脱NullReferenceException

c# properties null call
1个回答
1
投票

正如@ canton7所说,你回答了自己的问题。 ?.运算符实际上存在于C#中

这是一个小例子,展示了它如何阻止NullReferenceException

public class Program
{
    public static void Main(string[] args)
    {
        List<string> list = GetList();
        Console.WriteLine($"{list?.Count}");

        Console.ReadKey();
    }

    public static List<string> GetList()
    {
        return null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.