布尔?不可空

Pal*_*lmi 1 c# intellisense

我班上有以下内容:

public bool? EitherObject1OrObject2Exists => ((Object1 != null || Object2 != null) && !(Object1 != null && Object2 != null)) ? true : null;
Run Code Online (Sandbox Code Playgroud)

但是在Visual Studio中,我收到一个IntelliSense错误,即使该字段可以为空,也不能在"bool"和"NULL"之间进行转换.我做错了什么?有没有更清晰的方法来检查两个对象中的任何一个是否为空,但其中一个必须为空?

Ste*_*eve 5

尝试

? (bool?) true : null;
Run Code Online (Sandbox Code Playgroud)

问题是default bool(true)不可为空,因此就编译器而言,case语句返回不同的类型

您可以删除Servy指出的冗余

Object1 != null ^ Object2 != null
Run Code Online (Sandbox Code Playgroud)