c# - 为什么三元运算符和 if 语句返回不同的结果?

标签 c# .net .net-core c#-7.1

这个问题在这里已经有了答案:





Nullable DateTime used in property with expression returns unexpected default value

(2 个回答)


6 个月前关闭。




在下面的例子中,我返回一个 DateTimeOffset?使用 default value

var a = ConvertToDateTimeOffsetA(null); // 1/1/0001 12:00:00 AM +00:00
var b = ConvertToDateTimeOffsetB(null); // null

private static DateTimeOffset? ConvertToDateTimeOffsetA(DateTime? date)
{
    return date != null
        ? new DateTimeOffset(date.Value, TimeSpan.Zero)
        : default;
}
private static DateTimeOffset? ConvertToDateTimeOffsetB(DateTime? date)
{
    if (date != null) 
        return new DateTimeOffset(date.Value, TimeSpan.Zero);
    return default;
}
与 if 语句相比,为什么三元中返回的输出之间存在差异?
我的猜测是三元首先将类型强制为 DateTimeOffset然后内联转换回 Nullable<DateTimeOffset> ,但我不太确定为什么?

最佳答案

在三元版本中,它正在解释您的defaultdefault(DateTimeOffset) ,条件中的其他输出表达式类型。然后它将三元作为一个整体解释为可空的,它永远不会为空。
在第二种情况下,您的返回是使用 default(DateTimeOffset?) , 来自声明的返回类型。
在这种情况下,您可能希望在 default 中使用显式类型。表达式,或者:只需使用第二种形式并添加注释(最好是单元测试),这样以后就没有人“修复”它了。

关于c# - 为什么三元运算符和 if 语句返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67008839/

相关文章:

.net - NetTcpActivator 服务(Net.Tcp Listener Adapter)偶尔停止响应

c# - 将RichTextBox中的文本转换为语音

.net - Visibility.Collapse 在 WPF 中不起作用

asp.net-web-api - 调解器 Api 调用失败

c# - 防止控制台应用程序(.NET Core)在 VS2019 和 VS2022 中打印 "exited with code 0."

c# - 基于 Windows 8.1 构建的 .NET 4.0 程序集不适用于较低的 Windows 版本

c# - 使用c#的两个小数位

c# - 对于使用 .net 6.0 的 Azure 函数,我需要做什么将 PnP.Core.Services 替换为 CSOM

c# - 使用 javascript 从另一个按钮触发单击按钮事件

c# - 字符串格式说明文字