有没有人有关于执行 null 测试与在 try catch 中包装代码的指标?
我怀疑零测试更有效,但我没有任何经验数据。
环境为C#/.net 3.x,代码对比为:
Dude x = (Dude)Session["xxxx"];
x = x== null ? new Dude(): x;
对比
Dude x = null;
try {
x = (Dude)Session["xxxx"];
x.something();
} catch {
x = new Dude();
}
在 try catch 中包装有什么优势吗?
最佳答案
如果 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();
为异常(真正意外的事件)保存 try/catch。
关于c# - 空测试与 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874433/