c# - 如何检查嵌套引用中的空值

标签 c# c#-4.0 nullreferenceexception

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

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

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

第一种方法显然有效,但编码起来似乎有点乏味且难以阅读。第二种方法更容易一些,但可能不是为此使用异常处理的好主意。

是否有另一种检查空值并在必要时将空值分配给颜色的快捷方式?或者对在使用此类嵌套引用时如何避免 NullReferenceExceptions 有任何想法?

最佳答案

您正在寻找 null 安全的解引用运算符。

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

遗憾的是 C# 不支持它。也许稍后会添加,但目前还没有这样做的计划。

相关

关于c# - 如何检查嵌套引用中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10361868/

相关文章:

Wcf 回调 net tcp 双工只有 1 路故障

asp.net-mvc-4 - 如何错误处理NullReferenceException

c# - 为什么将动态对象类型转换为对象会抛出空引用异常?

c# - XML Serialazer C# Silverlight

C# for Windows Phone 7,为什么使用这种语言

null - C#4 : how to in-line detect for nulls?

android - 如何让用户一次只能从一台设备登录

c# - 将空值转换为类型

c# - C#:String.IndexOf到FileStream.Seek

c# - 剪贴板 SetText 失败而 SetDataObject 没有