I have a nullable double
MyNullableDouble = MyDouble == 0 ? null : MyDouble;
This is causing me an issue :
Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'double'
I have a nullable double
MyNullableDouble = MyDouble == 0 ? null : MyDouble;
This is causing me an issue :
Type of conditional expression cannot be determined because there is no implicit conversion between '' and 'double'
你应该 cast Mydouble
,否则在左边你有 typedouble?
而在右边你有double
,所以类型是不等价的(这正是异常所说的):
MyNullableDouble = MyDouble == 0 ? null : (double?)MyDouble;
是的,你不能这样做,这两个值都应该是相同的数据类型。使用第三的任何具体原因..使用 if else ...
您可以实施通用方法来处理此类情况。由于所有 Nullable 类型都有GetValueOrDefault
方法,因此您可以为非 Nullable 结构编写相反的方法:
public static T? GetNullIfDefault<T>(this T value)
where T: struct
{
if( value.Equals(default(T)))
{
return null;
}
return value;
}
使用示例:
MyNullableDouble = MyDouble.GetNullIfDefault();