有没有人有关于执行 null 测试与将代码包装在 try catch 中的指标?
我怀疑空测试更有效,但我没有任何经验数据。
环境为C#/.net 3.x,代码对比为:
Dude x = (Dude)Session["xxxx"];
x = x== null ? new Dude(): x;
versus
Dude x = null;
try {
x = (Dude)Session["xxxx"];
x.something();
} catch {
x = new Dude();
}
用 try catch 包装有什么优点吗?
如果 null 是可能的期望值,则测试 null。如果您不喜欢空测试并且有默认值,则可以使用空合并运算符来设置默认值:
// value is (Dude)Session["xxxx"] if not null, otherwise it's a new object.
Dude x = (Dude)Session["xxxx"] ?? new Dude();
保存 try/catch 来处理异常(真正的意外事件)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)