防止 C# 异常并找到更优雅的方法来检查可空值

Prevent C# exception and find more elegant way to make check for nullable value

CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.Value.ToShortDateString : null

这行代码抛出异常'Type of conditional expression cannot be determined because there is no implicit conversion between method group and null.'

是否有任何可行的方法来进行此检查和and/or更优雅(不那么丑陋)的方法?

注:

myObject = (dynamic)new
{
    CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.Value.ToShortDateString : null
}

您缺少方法调用的调用大括号 () 它应该是 ToShortDateString() 至于调用我们需要的方法,所以您的代码行应该如下所示:

CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate.ToShortDateString() : null ;

但是如果您使用的是 C# 6,则可以通过空传播运算符执行以下操作:

String CreatedDate = meta.CreatedDate?.ToShortDateString();

或:

String CreatedDate = meta.CreatedDate?.Value.ToShortDateString();

如果您低于 C# 6,请尝试:

String CreatedDate = meta.CreatedDate.HasValue ? meta.CreatedDate..ToShortDateString() ? null;

您可以使用 null-conditional 运算符:

CreatedDate = meta.CreatedDate?.ToShortDateString();