c# - 空测试与 try catch

标签 c#

有没有人有关于执行 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/

相关文章:

c# - ViewModel 的 POST 和 DomainModel 上的验证

c# - 如何在设计器中单击用户控件子项?

C#:按日期拆分字符串,保持日期不变

c# - 如何使用 Application.Resources 中定义的 DataTemplate?

c# - 如何在 dotnet core 中动态加载程序集

c# 如何使用 Microsoft Graph API 获取 Office 365 用户照片

c# - 如何在 .net 3.5 trackbar 中标记最小、最大、中心刻度?

c# - 我如何在 Unity3D 中进行触摸操作?

c# - 将选定的行 gridview 传递到另一个表单上的另一个 gridview

c# - 为纸牌分配号码