我有一个名为Investigation的数据库表.在此表中有一列名为INV.此列可以包含值0,1或null.
在我的应用程序中,有一个如下所示的if语句:
QNet.Investigation.DataContracts.Investigation investigation = Session["InvestigationObj"] as QNet.Investigation.DataContracts.Investigation;
if (investigation != null && investigation.INV != null && investigation.INV == true)
{
....
}
Run Code Online (Sandbox Code Playgroud)
在我看来,这有点矫枉过正,因为如果Investigation.INV == true,那么显然其他两个语句将不会为空.如果其他两个中的任何一个为null,那么investigation.INV也将为null.
我在这里错过了什么吗?原始开发人员是否有理由以这种方式创建if语句?岂不
if(investigation.INV == true)
{
...
}
Run Code Online (Sandbox Code Playgroud)
做同样的事情?
岂不
Run Code Online (Sandbox Code Playgroud)if(investigation.INV == true) { ... }
做同样的事情?
不,这将导致NullReferenceException
,如果investigation
是null
.这就是为什么你必须以任何方式检查null,无论是通过null-coalesce-operator还是使用你的 - 不可否认 - annyoing if语句或者什么.
换一种说法:
只是因为investigation
没有null
并不表示investigation.INV
是true
.它显然可以是false
甚null
至也可以.