假设,我有这个界面,
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) 在C#中,假设您希望在此示例中从PropertyC中提取值,而ObjectA,PropertyA和PropertyB都可以为null.
ObjectA.PropertyA.PropertyB.PropertyC
如何使用最少量的代码安全地获取PropertyC?
现在我会检查:
if(ObjectA != null && ObjectA.PropertyA !=null && ObjectA.PropertyA.PropertyB != null)
{
// safely pull off the value
int value = objectA.PropertyA.PropertyB.PropertyC;
}
Run Code Online (Sandbox Code Playgroud)
做更像这样的事情会很好(伪代码).
int value = ObjectA.PropertyA.PropertyB ? ObjectA.PropertyA.PropertyB : defaultVal;
Run Code Online (Sandbox Code Playgroud)
可能甚至进一步崩溃与空合并运算符.
编辑最初我说我的第二个例子就像js,但是我把它改成了psuedo-code,因为它被正确地指出它在js中不起作用.
c# nullable nullreferenceexception null-conditional-operator
我有以下丑陋的代码:
if (msg == null ||
msg.Content == null ||
msg.Content.AccountMarketMessage == null ||
msg.Content.AccountMarketMessage.Account == null ||
msg.Content.AccountMarketMessage.Account.sObject == null) return;
Run Code Online (Sandbox Code Playgroud)
有没有办法在C#中检查空值,以便我不必检查每个单独的级别?