Joh*_*hnB 3 c# if-statement nullpointerexception logical-operators
我经常在必要时执行此操作以防止空指针异常:
// Example #1
if (cats != null && cats.Count > 0)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
在#1中,我总是假设cats != null需要先行,因为操作顺序从左到右进行评估.
但是,与示例#1 不同,现在我想要做一些事情,如果对象是null或者如果Count是零,因此我使用逻辑OR而不是AND:
// Example #2
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
逻辑比较的顺序是否重要?或者我也可以反转顺序并获得相同的结果,例如在示例#3中?
// Example #3
if (table.Rows.Count <= 0 || table.Rows == null || table == null)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
(顺便说一下,我意识到我可以像下面那样重写#2,但我觉得它很乱,而且我仍然对OR运算符感到好奇)
// Example #4
if (!(table != null && table.Rows != null && table.Rows.Count > 0))
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*tta 11
在您提供的示例中:
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
......没有table.Rows,也table.Rows.Count将解除引用是否tables为空.
这是因为,使用C#逻辑运算符,运算顺序很重要.C#逻辑运算符是短路的 - 它们从左到右进行评估,如果任何结果导致表达式的其余部分没有实际意义,那么表达式的其余部分将不会被评估.
考虑以下代码:
bool A()
{
return false;
}
bool B()
{
return true;
}
//...
if (A() && B())
{
// do something
}
Run Code Online (Sandbox Code Playgroud)
要使AND子句为true,所有元素都必须为true.但是,A()返回false,运行时(或者在优化步骤中可能是编译器,但不要担心...)根本不会进行评估B().
OR(||)表达式也是如此.如果子句中的任何元素为true,则从左到右进行计算,则不会执行该子句的其余部分.