假设,我有这个界面,
interface IContact
{
IAddress address { get; set; }
}
interface IAddress
{
string city { get; set; }
}
class Person : IPerson
{
public IContact contact { get; set; }
}
class test
{
private test()
{
var person = new Person();
if (person.contact.address.city != null)
{
//this will never work if contact is itself null?
}
}
}
Run Code Online (Sandbox Code Playgroud)
Person.Contact.Address.City != null (这可以检查City是否为空.)
但是,如果Address或Contact或Person本身为null,则此检查将失败.
目前,我能想到的一个解决方案是:
if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != …Run Code Online (Sandbox Code Playgroud)