只需空检查 + 属性 访问

Simply null check + property access

C#中有没有运算符来简化这个操作,避免空指针异常?

obj == null ? null : obj.Property;

类似于

obj?.Property;

我真的很想摆脱 NullReferenceExeptions

正如@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;
    }
}