Xai*_*oft 1 exception-handling
假设我有以下类层次结构:
Person对象包含Customer对象,Customer对象包含Address对象.
我不在乎客户是否有地址,但如果他们这样做,我想将其保存到数据库中.所以在这种情况下,拥有类似的东西是完美的:
try
{
Address addr = person.Customer.Address;
db.SaveAddress(addr);
}
catch
{
//I don't care, but if it is there, just save it.
}
Run Code Online (Sandbox Code Playgroud)
在上面,我不在乎Customer是null还是Address为null.我有另一种选择
if(person.Customer != null)
{
if(person.Customer.Address != null)
{
}
}
Run Code Online (Sandbox Code Playgroud)
如果层次结构很长,上述情况可能会很长.是否有更优雅的方法来检查对象链是否为null而不必检查每个对象.
对于特殊情况,您应始终使用例外.您将受到性能损失,因为CPU上会有一些上下文切换.
你可以将第二个例子与大多数短路语言结合起来.
if(person.Customer != null && person.Customer.Address != null)
{
}
Run Code Online (Sandbox Code Playgroud)
例:
bool isAddressValid = person.Customer != null && person.Customer.Address != null;
if (isAddressIsValid) { }
Run Code Online (Sandbox Code Playgroud)
上下文切换:http://en.wikipedia.org/wiki/Context_switch
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |