如何在嵌套引用中检查null [英] How to check for null in nested references

查看:249
本文介绍了如何在嵌套引用中检查null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一些最佳实践指南。让我们假设我有一行这样的代码:

Looking for some best-practice guidance. Let's say I have a line of code like this:

Color color = someOrder.Customer.LastOrder.Product.Color;

其中Customer,LastOrder,Product和Color可以 null 正常条件下。我想颜色为null,如果路径中的任何一个对象为null,但是;为了避免空引用异常,我需要检查每个对象的空条件,例如

where Customer, LastOrder, Product, and Color could be null under normal conditions. I'd like color to be null if any one of the objects in the path is null, however; in order to avoid null reference exceptions, I'd need to check for the null condition for each one of the objects, e.g.

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) {}

第一种方法很明显,但是看起来代码更繁琐,阅读更困难。第二种方法有点简单,但是可能不是一个好主意,为此使用异常处理。

The first method clearly works, but it seems a bit more tedious to code and harder to read. The second way is a bit easier but probably not a good idea to use exception handling for this.

有另一种快捷方式检查null和分配null到颜色if必要?或者关于如何在使用这样的嵌套引用时如何避免NullReferenceExceptions的任何想法?

Is there another shortcut way of checking for nulls and assigning null to color if necessary? Or any thoughts on how to avoid NullReferenceExceptions when using such nested references?

推荐答案

您正在寻找null安全解引用操作符。

You are looking for the null-safe dereferencing operator.

Color color = someOrder?.Customer?.LastOrder?.Product?.Color;

不幸的是C#不支持它。

Unfortunately C# doesn't support it. Maybe it will be added later, but there are no plans to do that at the moment.

相关

  • Deep Null checking, is there a better way?

这篇关于如何在嵌套引用中检查null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆