我有一个非常简单的片段代码,其中包含一个foreach循环:
foreach(var item in list) {
var valueForPropertyA = getPropertyAValue(item?.Id ?? 0);
if(valueForPropertyA == null) {
continue;
}
item.PropertyA = new PropertyADto(valueForPropertyA);
}
Run Code Online (Sandbox Code Playgroud)
我们也有一些自动代码检查工具,它给了我下面的警告在上面的代码:
'item' is null on at least one execution path
有没有可能是一个item在list为null还是我误解的警告?
当然,foreach不会跳过那些物品null.那你就得到了一条NullReferenceException线item.PropertyA = new PropertyADto(valueForPropertyA);.
相反,你可以使用
foreach(var item in list.Where(i => i != null))
{
// ...
}
Run Code Online (Sandbox Code Playgroud)