合并可以为空的对象的属性?

时间:2018-05-30 09:24:05

标签: c# nullable

您好有没有办法制定如下所示的条件? 如果field为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

2 个答案:

答案 0 :(得分:7)

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

equality operator
public bool IsFilled => this.nodeBuffer?.IsFilled == true;

Nullable类型支持所有非可空类型支持的运算符,称为lifted operator

答案 1 :(得分:0)

this.nodeBuffer?.IsFilled会返回Nullable<T>,因此您可以使用GetValueOrDefault()方法,如果false则为null

所以你的属性定义如下所示:

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