寻找布尔语句的解释

Looking for explanation of a boolean statement

我在我正在使用的库中找到了这个语句。它应该检查集群中的当前节点是否是领导者。这是语句:(!(cluster.Leader?.IsRemote ?? true))

为什么不直接使用 (cluster.Leader?.IsRemote)? (忽略 ! 运算符,我知道它是如何工作的)

这种方法有什么好处吗?

表示如果cluster.Leader?.IsRemotenull那么认为是真的?? true

实际上 null ?? true 等于 true

因此,如果您的 leader 为空,则整个语句将 return 为假)。没有 ?? null 你的语句甚至不会编译,因为 !null 没有任何意义。

考虑以下代码:

public class Foo
{
    public bool IsBar { get; set; }
}

var foo = new Foo();

Console.WriteLine(!(foo?.IsBar ?? true));

虽然 IsBar 被声明为常规的、不可为 null 的布尔值,但 foo?.IsBar 中的 ? 运算符使该表达式的类型为 bool?,而不是 bool.

您不能在布尔表达式中使用可为 null 的布尔值,另请参阅 if condition with nullable,因此您需要使表达式明确:如果 foo 应该发生什么,因此 foo?.IsBarnull?

这就是 ?? true 的用武之地。备选方案:

Console.WriteLine(!(foo?.IsBar).GetValueOrDefault(true));
Console.WriteLine(foo?.IsBar == false);

让我们为

建立一个真相table
 (!(cluster.Leader?.IsRemote ?? true))

构造(请注意,我们有 三个 值需要考虑:truefalsenull):

 (!(cluster.Leader?.IsRemote ?? true)) : Result 
 ----------------------------------------------
                                  true : false
                                 false :  true <- the only true we have
                                  null : false

所以,如果您正在寻找简化,您可以把它写成

 (cluster.Leader?.IsRemote == false)

让我们考虑以下代码

class Program
{
    static void Main(string[] args)
    {
        Cluster cluster = new Cluster { Leader = null };
        var libresult = (!(cluster.Leader?.IsRemote ?? true));
        var result = (!(cluster.Leader?.IsRemote));
    }

}

class Cluster
{
   public Leader Leader { get; set; }
}

class Leader
{
    public bool IsRemote { get; set; }
}

如你所见Leader 在上面的代码中为空

如果考虑条件为

var result = (!(cluster.Leader?.IsRemote));

然后

Null-conditional/Elvis operator(?.)

return null 对于 cluster.Leader?.IsRemote 所以,!(null) 将是 null.

但如果考虑条件为

var libresult = (!(cluster.Leader?.IsRemote ?? true));

然后正如我们在上面看到的 Null-conditional/Elvis operator(?.) return null for cluster.Leader?.IsRemote 所以,现在条件是 !(null ?? true)

根据

Null-collation(??) operator

(null ?? true) 将 return true。并且 !(true) 将是 false

so, benefit of "?? true" is that if left hand side value is null then it should be consider as Boolean(true).