[英]Cast to bool nullable of null value VS default value of bool nullable
[英]Why can the null conditional operator be used when setting the value of a bool without using a nullable bool?
我有以下代码行:
user.Exists = await this.repository?.Exists(id);
左侧Exists
是User
类的属性。 它的类型只是bool
,而不是bool?
。 右侧的Exists
方法是一种API方法,用于检查存储库中是否存在给定实体。 它返回Task<bool>
。 我想先检查存储库是否为null,因此我使用null条件运算符。 我认为如果存储库为null,那么整个右侧只会返回null,这不能分配给bool
类型,但编译器似乎没问题。 是否只是以某种方式默认为错误值?
问题在于等待。 可以在await之前发生nullable,所以它就像await (this.repository?.Exists(id))
,当this.repository为null时,变成await (null?.Exists(id))
,变成await (null)
,崩溃了。 ?。 无法进入Task<bool>
并使其成为Task<bool?>
。
因此,您将获得正确的布尔值或异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.