在C#bool?x =真; if(x == true)看起来很尴尬

Ham*_*jan 4 c#-4.0

bool? x = true;
if (x == true)
Run Code Online (Sandbox Code Playgroud)

看起来很尴尬.

但有时这正是所需要的.

有没有更好的办法?

编辑:

谢谢大家的尝试,但到目前为止,我还没有找到一种能够击败原版的方法.我想我只需要处理尴尬,或者评论一下.

jba*_*all 8

根据您的具体情况,您可能希望使用空合并运算符,该运算符允许您指定bool?未设置的默认值.它并不比你的条件短,但我认为它很有用:

if(x ?? true) //defaults to true if x is not set
Run Code Online (Sandbox Code Playgroud)

或者,直接复制您的案例(并由于受欢迎的需求):

if(x ?? false) //defaults to false if x is not set
Run Code Online (Sandbox Code Playgroud)