null test与try catch

mso*_*son 10 c#

有没有人在try catch中执行null测试与包装代码的指标?

我怀疑null测试效率更高,但我没有任何经验数据.

环境是C#/.net 3.x,代码比较如下:

Dude x = (Dude)Session["xxxx"];
x = x== null ? new Dude(): x;
Run Code Online (Sandbox Code Playgroud)

Dude x = null;
try {
    x = (Dude)Session["xxxx"];
    x.something();
} catch {
    x = new Dude();
}
Run Code Online (Sandbox Code Playgroud)

包裹在try catch中有什么好处吗?

Jus*_*ner 23

如果null是可能的预期值,则测试null.如果您不喜欢null测试并且具有默认值,则可以使用null coelescing运算符来设置默认值:

// value is (Dude)Session["xxxx"] if not null, otherwise it's a new object.
Dude x = (Dude)Session["xxxx"] ?? new Dude();
Run Code Online (Sandbox Code Playgroud)

保存try/catch for Exceptions(真正意外的事件).

  • +1,永远不要使用程序控制流程的异常.你想要创建例外的唯一时间是if(Dude)Session ["xxxx"]; 为null会导致停止您所在方法的运行.即,如果null值会阻止该方法成功完成它被调用执行的函数.在你写这个问题的时候,如果在这种情况下你需要做的就是继续创建一个新的Dude(),那么情况并非如此,所以不保证例外. (2认同)

Mik*_*ier 9

如果紧凑的代码是你真正想要的,你可以:

Dude x = Session["xxxx"] as Dude ?? new Dude();
Run Code Online (Sandbox Code Playgroud)

??如果有的话,运算符将返回两个值的第一个非空值.

谢谢