gpt4 book ai didi

c# - 如何对可为空的日期使用空合并运算符

转载 作者:太空狗 更新时间:2023-10-29 22:21:32 25 4
gpt4 key购买 nike

我的 View 模型有一个可为空的日期属性,例如...

[DataType(DataType.Date)]
public DateTime? SanctionExpires { get; set; }

但是当我尝试使用 null 合并运算符时,例如...

var test = model.SanctionExpires.Value.ToUniversalTime() ?? model.SanctionExpires;

我收到以下错误...

operator '??' cannot be applied to operands of type 'datetime' and 'datetime'

我认为这应该可行,因为我将我的日期属性设置为可为空并且 this post建议它也应该工作。我做错了什么?

更新

为了更加清晰,我想使用 null-coaslescing 来分配一个 Dapper 参数,该参数将更新我的数据库中的 DateTime 字段。该字段可以接受空值或日期时间值。基本上,如果用户指定日期,则将提供的日期分配给参数,否则分配 null...

p.Add("@SanctionExpires", model.SanctionExpires.Value.ToUniversalTime() ?? model.SanctionExpires);

请注意,我必须进行 UTC 转换,因为我使用的 SQL Azure 将 UTC 用于日期,否则如果我只是从本地系统传递数据,我的时间将超过 11 小时(我在澳大利亚)。在 sql 中,我使用一个函数在更新表之前将日期偏移到我的时区。

我目前让它工作的解决方案如下,但不确定这是否是最干净的方法。能排成一行就好了……

if (model.SanctionExpires == null)
p.Add("@SanctionExpires", model.SanctionExpires);
else
p.Add("@SanctionExpires", model.SanctionExpires.Value.ToUniversalTime());

最佳答案

.Value 假定它不能为 null。因此,在其上应用空合并运算符是无用且被禁止的。

您可以像这样使用运算符,但是继续您的代码我不确定这是否是您需要的:

DateTime test = (model.SanctionExpires ?? DateTime.Now).ToUniversalTime();

对于您的更新:您可以像这样简化评估:

DateTime? test = model.SanctionExpires?.ToUniversalTime();

关于c# - 如何对可为空的日期使用空合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40787281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com