有没有人在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(真正意外的事件).
如果紧凑的代码是你真正想要的,你可以:
Dude x = Session["xxxx"] as Dude ?? new Dude();
Run Code Online (Sandbox Code Playgroud)
??如果有的话,运算符将返回两个值的第一个非空值.
谢谢
| 归档时间: |
|
| 查看次数: |
3448 次 |
| 最近记录: |