[英]How to avoid many null checks for a hierarchy of associated/composed/aggregated objects before a foreach loop?
What is the best way to check for nulls in this situation?在这种情况下检查空值的最佳方法是什么?
foreach(var item in Vehicles.Car.CarModel)
{
...
...
}
Now the Car or CarModel can be Null and should be checked somehow.现在 Car 或 CarModel 可以是 Null 并且应该以某种方式检查。 What is the best way?
什么是最好的方法?
You can write this to avoid some null checks in two lines before the loop:您可以编写此代码以避免在循环之前在两行中进行一些 null 检查:
TypeOfCarModel items = Vehicles?.Car?.CarModel ?? null;
if ( items != null )
foreach ( var item in items )
{
}
This use Null-conditional and Null-coalescing operators.这使用Null 条件和Null 合并运算符。
In case of a list, for example, or any other thing like that, a variant may be:例如,在列表或任何其他类似的情况下,变体可能是:
List<CarModelItem> items = Vehicles?.Car?.CarModel ?? new List<CarModelItem>();
foreach ( var item in items )
{
}
It avoids the null check because the " IEnumerable
" is empty, but it creates an instance...它避免了 null 检查,因为“
IEnumerable
”为空,但它创建了一个实例......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.