在获取 Count 之前检查 List 是否为 Null 会导致 -> Cannot implicitly conversion type 'int?' 到'int

tec*_*hno 0 c# .net-core asp.net-core

我正在尝试查找列表中存在的项目数。为了防止 null 异常。我使用运算符在获取其计数之前?检查是否 myBenchmarkMappings为 null。

 int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings?.Count;
Run Code Online (Sandbox Code Playgroud)

但这会导致Cannot implicitly convert type 'int?' to 'int'.异常

我究竟做错了什么 ?

Ale*_*ova 10

这是因为该?运算符将返回值 or null。而且你不能分配null给 int。
你有两个选择。首先是将其标记intnullable。但在后一种情况下,您需要检查是否int为空。

int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;

if (benchmarkAccountCount == null) 
{
    // null handling
}
Run Code Online (Sandbox Code Playgroud)

我认为第二个选项更好,您可以使用空合并运算符并在列表为 时??给出默认值。benchmarkAccountCountnull

int benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count ?? 0;
Run Code Online (Sandbox Code Playgroud)