希望得到一些最佳实践指导。假设我有一行像这样的代码:
Color color = someOrder.Customer.LastOrder.Product.Color;
在正常情况下,客户、最后订单、产品和颜色可能为null
。然而,如果路径中的任何一个对象为空,我希望颜色也为空;为了避免空引用异常,我需要检查每个对象的空条件,例如:
Color color = someOrder == null ||
someOrder.Customer == null ||
someOrder.Customer.LastOrder == null ||
someOrder.Customer.Product == null ?
null : someOrder.Customer.LastOrder.Product.Color;
或者我可以这样做
Color color = null;
try {color = someOrder.Customer.LastOrder.Product.Color}
catch (NullReferenceException) {}
第一种方法显然可行,但编写起来可能有些繁琐,阅读起来也更加困难。第二种方法稍微容易一些,但使用异常处理来处理这个问题可能不是一个好主意。还有其他检查null并在必要时将null分配给颜色的捷径吗?或者对于使用嵌套引用时如何避免NullReferenceExceptions有什么想法吗?