C#6空条件检查

时间:2016-06-23 00:34:45

标签: c# c#-6.0 null-propagation-operator

如何将其转换为C#6 Null条件检查?

var durationhours = product.ProductAudioAsset.TotalLengthInSeconds != null
    ? (short?)TimeSpan.FromSeconds(product.ProductAudioAsset.TotalLengthInSeconds.Value).TotalHours
    : null;

其中TotalLengthInSeconds可以为空

1 个答案:

答案 0 :(得分:5)

您可以创建一个扩展方法来帮助:

public static short SecondsAsTotalHours(this short value)
{
    return (short)TimeSpan.FromSeconds(value).TotalHours;
}

然后你可以这样做:

var durationhours = product.ProductAudioAsset.TotalLengthInSeconds?.SecondsAsTotalHours();