bool?
实际上是 Nullable<Boolean>
类型,可以当作三值的 bool
类型来使用。不过三值的布尔进行与或运算时的结果与二值有什么不同吗?
在 [C# 重载条件逻辑运算符(&& 和 | )](/post/overload-conditional-and-and-or-operators-in-csharp) 一文中我说明了如何重载条件逻辑运算符 && 和 ||。 |
---|
这两个运算符不能直接重载,但可以通过重载 &
和 |
运算符来间接完成。
对于 bool?
,重载了这样两个运算符:
bool? operator &(bool? x, bool? y)
bool? operator |(bool? x, bool? y)
于是我们可以得到三值 bool?
的与或结果。
x | y | x&y | x|y |
---|---|---|---|
true | true | true | true |
true | false | false | true |
true | null | null | true |
false | true | false | true |
false | false | false | false |
false | null | false | null |
null | true | null | true |
null | false | false | null |
null | null | null | null |
参考资料
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 吕毅 (包含链接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (walter.lv@qq.com) 。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有