新的 C# 6.0 空条件运算符是编写更简洁、更简单的代码的便捷工具。假设有一组客户,那么如果 customers
为 null 使用此(来自 MSDN 的示例),您可以获得 null 而不是长度:
int? length = customers?.Length;
类似地,你可以得到 null 而不是 customer :
Customer first = customers?[0];
对于更详细的表达式,如果 customers
为 null,第一个客户为 null,或者第一个客户的 Orders
对象为 null,则返回 null:
int? count = customers?[0]?.Orders?.Count();
但是还有一个有趣的客户不存在的案例,null 条件运算符似乎没有解决这个问题。我们在上面看到覆盖了 null 客户,即如果 customers
数组中的条目为 null。但这与不存在的客户截然不同,例如在 3 元素数组中查找客户 5
或在 0 元素列表中查找客户 n
。 (请注意,同样的讨论也适用于字典查找。)
在我看来,null 条件运算符只专注于否定 NullReferenceException 的影响; IndexOutOfRangeException 或 KeyNotFoundException 是孤独的,暴露的,蜷缩在角落里,需要自生自灭!我认为,本着空条件运算符的精神,它也应该能够处理这些情况……这引出了我的问题。
我错过了吗? null 条件是否提供任何优雅的方式来真正覆盖此表达式...
customers?[0]?.Orders?.Count();
...什么时候没有第零个元素?
最佳答案
不,因为它是一个null-条件运算符,而不是一个indexoutofrange-条件运算符,并且只是类似于以下内容的语法糖:
int? count = customers?[0]?.Orders?.Count();
if (customers != null && customers[0] != null && customers[0].Orders != null)
{
int count = customers[0].Orders.Count();
}
您可以看到,如果没有第 0 个客户,您将得到常规的 IndexOutOfRangeException
。
您可以解决它的一种方法是使用一个扩展方法来检查索引并在索引不存在时返回 null:
public static Customer? GetCustomer(this List<Customer> customers, int index)
{
return customers.ElementAtOrDefault(index); // using System.Linq
}
那么您的支票可能是:
int? count = customers?.GetCustomer(0)?.Orders?.Count();
关于c# - "nullify"数组元素存在的空条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040372/