与可空对象的 属性 合并?

Coalesce with property of nullable object?

您好,有什么方法可以制定如下所示的条件吗? 如果字段为 null 那么 false else field.Property ?

class Node
{
    public bool IsFilled;
}

class Holder
{
    Node nodeBuffer;
    public bool IsFilled => this.nodeBuffer?.IsFilled ?? false; 
}

我怎么说 if nodeBuffer is null then false else nodeBuffer.IsFilled

是的,您可以使用与 Nullable<bool>

一起使用的 equality operator
public bool IsFilled => this.nodeBuffer?.IsFilled == true;

可空类型支持其非可空类型支持的所有运算符,即:lifted operator

this.nodeBuffer?.IsFilled returns 一个 Nullable<T> 所以你可以在上面使用 方法所以它会是 false 如果 null

因此您的 属性 定义如下所示:

public bool IsFilled => (this.nodeBuffer?.IsFilled).GetValueOrDefault();