我有以下代码行:
user.Exists = await this.repository?.Exists(id);
Exists
左侧是 User
的属性类(class)。它的类型只是 bool
, 不是 bool?
. Exists
右侧的方法是一种 API 方法,用于检查存储库中是否存在给定实体。它返回 Task<bool>
.我想先检查存储库是否为 null,所以我使用 null 条件运算符。我认为如果存储库为 null,那么整个右侧将只返回 null,不能将其分配给 bool
。类型,但编译器似乎没问题。它是否只是以某种方式默认为假值?
最佳答案
问题是等待。可为空发生在等待之前,所以它就像 await (this.repository?.Exists(id))
,当 this.repository 为 null 时,变为 await (null?.Exists(id))
, 变成 await (null)
,它崩溃了。这 ?。无法进入 Task<bool>
并制作它Task<bool?>
.
因此您将获得正确的 boolean 值或异常。
关于c# - 为什么在不使用可为空的 bool 的情况下设置 bool 的值时可以使用 null 条件运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557632/