C# foreach中的项可以为null吗

C# foreach中的项可以为null吗,c#,C#,我有一个非常简单的片段代码,其中包含一个foreach循环: foreach(var item in list) { var valueForPropertyA = getPropertyAValue(item?.Id ?? 0); if(valueForPropertyA == null) { continue; } item.PropertyA = new PropertyADto(valueForPropertyA); } 我们还有一些

我有一个非常简单的片段代码,其中包含一个foreach循环:

foreach(var item in list) {
    var valueForPropertyA = getPropertyAValue(item?.Id ?? 0);

    if(valueForPropertyA == null) {
        continue;
    }

    item.PropertyA = new PropertyADto(valueForPropertyA);
}
我们还有一些自动代码检查工具,它对上述代码给出以下警告:
“项”在至少一个执行路径上为空

列表中的
是否可能为
,或者我是否误解了警告?

参考项和
可空
值类型可以为空-但您可以手动跳过它们

foreach(var item in list.Where(x => x != null))

要回答您的主要问题,可以,如果由
foreach
循环枚举的
IEnumerable
包含引用类型,则它们可以为空。例如,
List
可能包含空条目,因为
string
可以为空

我怀疑您在至少一条执行路径上收到的
'item'为null的原因是由于在以下行中使用了null传播运算符:

var valueForPropertyA = getPropertyAValue(item?.Id ?? 0);
稍后你打电话:

item.PropertyA = new PropertyADto(valueForPropertyA);

第一行的
item?.Id
表示您希望
item
可能为空。第二行不包括null传播运算符,因此代码分析工具警告您,虽然第一行的
可能为null,但您没有在第二行处理这种可能性。

当然,
foreach
不会跳过
null
项。然后在
item.PropertyA=newpropertyadto(valueForPropertyA)行获得一个
NullReferenceException

相反,你可以使用

foreach(var item in list.Where(i => i != null))
{
    // ...
}

当然,
foreach
不会跳过空项。然后您将在
item.PropertyA
处获得一个
NullReferenceException
。有趣的是,您已经使用了
item?.Id??0
。相反,您应该使用
foreach(列表中的var项。其中(i=>i!=null)){}
@Rafalon项是一个对象