这个if语句是否过度杀伤?

com*_*umb -3 c# if-statement

我有一个名为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)

做同样的事情?

Him*_*ere 6

岂不

if(investigation.INV == true)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

做同样的事情?

不,这将导致NullReferenceException,如果investigationnull.这就是为什么你必须以任何方式检查null,无论是通过null-coalesce-operator还是使用你的 - 不可否认 - annyoing if语句或者什么.

换一种说法:

只是因为investigation没有null并不表示investigation.INVtrue.它显然可以是falsenull至也可以.

  • 用于回答OP的真实问题的+1(或者至少看起来是他/她的真实问题)*. (2认同)