避免 NullReferenceExceptions
var person = new Person
{
Address = null;
};
var city = person.Address.City; //throws a NullReferenceException
var nullableCity = person.Address?.City; //returns the value of null
這種效果可以連結在一起:
var person = new Person
{
Address = new Address
{
State = new State
{
Country = null
}
}
};
// this will always return a value of at least "null" to be stored instead
// of throwing a NullReferenceException
var countryName = person?.Address?.State?.Country?.Name;