三元运算符C#速记

时间:2019-06-10 06:36:24

标签: c# ternary-operator

我有一个类Segment,它有四个类PricingDetailPer PricingDetailPerAdultPricingDetailPerChildPricingDetailPerSeniorPricingDetailPerInfant的实例,它们都具有属性{{1 }}。

在代码中,我需要获取属性Availability,但是我需要检查Parent是否存在。是否有这样的速记:

Availability

return segment.PricingDetailPerAdult != null ? (this.Availability) : (continue checking); 是指this还是我检查的其他某些属性?

1 个答案:

答案 0 :(得分:1)

return segment.PricingDetailPerAdult?.Availability
       ?? segment.PricingDetailPerChild?.Availability
       ?? segment.PricingDetailPerSenior?.Availability
       ?? segment.PricingDetailPerInfant?.Availability;

参考:

Null-conditional operators ?. and ?[]
?? operator