所以我有一个Retrieve()函数,它可以获取一个对象或null(如果找不到该对象)。我正在使用带有该对象的布尔属性的if语句。它的设置就是这样。
if(Retrieve(index).IsForm == true) {}
这个问题是,如果找不到对象,它将抛出一个空引用异常。当然,有一些方法,但我没有简明扼要。有一个尝试......捕获,但是当我期待错误时,这似乎毫无意义。我可以先检查对象是否为空,if(Retrieve(index) != null)
,但这似乎是在添加不必要的嵌套。有一个聪明的方法来处理这个?我想过使用空合并运算符,但在这种情况下它不起作用。
答案 0 :(得分:2)
您可以调用该方法两次:
if(Retrieve(index) != null && Retrieve(index).IsForm == true) { }
或者您可以将行分开并将结果存储在if:
之前var result = Retrieve(index);
if(result != null && result.IsForm == true) { }
答案 1 :(得分:2)
您可以编写IsForm
函数为您执行这两项操作:
bool IsForm(int index)
{
var result = Retrieve(index);
return result != null && result.IsForm;
}
if (IsForm(index))
...
答案 2 :(得分:1)
Null对象模式在这里会有所帮助。它可以使您的调用代码保持干净,但会添加一个额外的类。
class NullWhatever : Whatever
{
public NullWhatever() { IsForm = false; }
}
Whatever Retrieve(...)
{
...
return new NullWhatever(); // instead of null
}
答案 3 :(得分:1)
您可以制作Nullable_IsForm扩展方法。然后你可以检查空状态。
public static class RetrieveExtension
{
public static bool? Nullable_IsForm(this Retrieve retrieved)
{
if(retrieved == null)
{
return null;
}
else
{
return retrieved.IsForm;
}
}
}
然后在您的代码中,您将根据bool
值
if(Retrieve(index).Nullable_IsForm == true)
{}
else if (Retrieve(index).Nullable_IsForm == false)
{}
else if (Retrieve(index).Nullable_IsForm == null )
{}
答案 4 :(得分:0)
我认为没有更简洁的方法可以做到这一点,不。
我能想到的最短的是:
if(Retrieve(index)!=null && Retrieve(index).IsForm == true) {}
但我不喜欢这样,因为它多次调用Retrieve(index)
。我会去
var foo = Retrieve(index);
if(foo!=null && foo.IsForm == true) {}
但这显然没有做任何聪明或更简洁的事情。它可能比某些替代品更有效。
答案 5 :(得分:0)
您可以将两个条件放在同一个if
:
if(Retrieve(index)!= null && Retrieve(index).IsForm == true) {}
由于短路,如果空检查失败,则不评估表达式的其余部分。