Avatar ·

C#中的null/nil是什么以及如何处理它?

大家好!我开始学习C#,遇到了null的概念。在其他语言中我见过nil或None,但在C#中似乎是一样的。请告诉我,null在引用类型的上下文中具体是什么意思,以及如何正确处理它?

我尝试写简单的代码,但遇到了NullReferenceException。例如:

public class Person { public string Name { get; set; } }

Person person = null;
Console.WriteLine(person.Name); // 错误:Object reference not set to an instance of an object.

我期望person.Name返回空字符串或null而不抛出异常。如何避免这类错误?我尝试过用if (person != null)检查,但这让代码变得冗长。我听说过?. (null-conditional operator)和?? (null-coalescing operator)——如何正确使用它们?另外,null和default有什么区别?