【发布时间】:2011-04-22 02:50:01
【问题描述】:
为了防止空指针异常,我经常这样做:
// Example #1
if (cats != null && cats.Count > 0)
{
// Do something
}
在 #1 中,我一直假设 cats != null 需要排在第一位,因为运算顺序是从左到右计算的。
但是,不像示例 #1,如果对象是 null 或者如果 Count 为零,我想做一些事情,因此我使用逻辑 OR 而不是 AND:
// Example #2
if (table == null || table.Rows == null || table.Rows.Count <= 0)
{
// Do something
}
逻辑比较的顺序重要吗?或者我也可以颠倒顺序并获得相同的结果,例如示例 #3?
// Example #3
if (table.Rows.Count <= 0 || table.Rows == null || table == null)
{
// Do something
}
(顺便说一句,我意识到我可以像下面这样重写#2,但我认为它很乱,我仍然对 OR 运算符感到好奇)
// Example #4
if (!(table != null && table.Rows != null && table.Rows.Count > 0))
{
// Do something
}
【问题讨论】:
标签: c# if-statement nullpointerexception logical-operators