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。
你有两个选择。首先是将其标记int
为nullable
。但在后一种情况下,您需要检查是否int
为空。
int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;
if (benchmarkAccountCount == null)
{
// null handling
}
Run Code Online (Sandbox Code Playgroud)
我认为第二个选项更好,您可以使用空合并运算符并在列表为 时??
给出默认值。benchmarkAccountCount
null
int benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count ?? 0;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
493 次 |
最近记录: |