为什么在不使用可空bool的情况下设置bool的值时可以使用null条件运算符?

Dre*_*rew 5 c# boolean nullable null-conditional-operator

我有以下代码行:

user.Exists = await this.repository?.Exists(id);
Run Code Online (Sandbox Code Playgroud)

Exists在左侧是User班级的财产.它的类型只是bool,而不是bool?.Exists右侧的方法是一种API方法,用于检查存储库中是否存在给定实体.它回来了Task<bool>.我想先检查存储库是否为null,因此我使用null条件运算符.我认为如果存储库为null,那么整个右侧只返回null,这不能分配给一个bool类型,但编译器似乎没问题.是否只是以某种方式默认为错误值?

小智 8

问题在于等待.可以在await之前发生nullable,所以它就像是await (this.repository?.Exists(id)),当this.repository为null时,变成了await (null?.Exists(id))变成await (null)崩溃的变量.?.没有能力进入Task<bool>并制造它Task<bool?>.

因此,您将获得正确的布尔值或异常.