Bri*_*n J 7 c# model-view-controller datetime nullable null-coalescing-operator
我正在读回DateTime?从我看来的价值.现在我检查一下NextUpdateDateTime?HasValue如果是这样,将时间转换为UTC.
从阅读起来看来,我似乎需要使用a null coalescing operator但是我的任务告诉我System.NUllable不包含ToUniversalTime()使用该运算符时的定义.
我在SO上搜索了类似的问题,但没有运气.
题:
如何将null DateTime值转换为UTC?
码:
我只是检查DateTime?有一个值,如果是这样,将DateTie转换为UTC -
if (escalation.NextUpdate.HasValue)
{
escalation.NextUpdate = escalation.NextUpdate ?? escalation.NextUpdate.ToUniversalTime();
}
else
{
escalation.NextUpdate = null;
}
Run Code Online (Sandbox Code Playgroud)
我NextUpdate在模型中的属性:
public DateTime? NextUpdate { get; set; }
Run Code Online (Sandbox Code Playgroud)
Ren*_*ogt 12
您的代码错误的方式不止一种.
该??运算符返回左边如果它不为空,否则右侧.
既然你已经检查过escalation.NextUpdate.HasValue的true,左侧是不是null和您再次分配相同的日期(不转换为UTC).
Nullable<DateTime>没有声明ToUniversalTime(),你需要在价值上做到这一点.
所以最终的代码应如下所示:
if (escalation.NextUpdate.HasValue)
escalation.NextUpdate = escalation.NextUpdate.Value.ToUniversalTime();
Run Code Online (Sandbox Code Playgroud)
或者使用C#6
escalation.NextUpdate = escalation.NextUpdate?.ToUniversalTime();
Run Code Online (Sandbox Code Playgroud)
无论如何都不需要else分支null.
如果您使用的是c#6,那么它非常简单
escalation.NextUpdate?.ToUniversalTime();
Run Code Online (Sandbox Code Playgroud)
这转换为好像NextUpdate不为null调用ToUniversalTime()else返回null
如果你不能使用c#6那么内联可能是你最好的选择
escalation.NextUpdate.HasValue ? (DateTime?)escalation.NextUpdate.Value.ToUniversalTime():null;
Run Code Online (Sandbox Code Playgroud)
这基本上与你的完全一样,如果你错过了你可以错过了可空的Value属性并且纠正了你使用的?操作者
| 归档时间: |
|
| 查看次数: |
4355 次 |
| 最近记录: |