私はこのインターフェースを持っているとします。
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?
}
}
}
Person.Contact.Address.City != null
(これは City が null かどうかを確認するために機能します。)
ただし、Address または Contact または Person 自体が null の場合、このチェックは失敗します。
現在、私が考えることができる1つの解決策はこれでした:
if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)
{
// Do some stuff here..
}
これを行うよりクリーンな方法はありますか?
null
としてチェックが行われるのは本当に好きではありません(something == null)
。代わりに、メソッドのようなことを行う別の良い方法はありsomething.IsNull()
ますか?