没有DateTime?.ToString(string)重载?
我知道以自定义格式显示DateTime
的标准过程,如下所示:
MessageBox.Show(dateSent.ToString("dd/MM/yyyy hh:mm:ss"));
但是,当我将变量从DateTime
更改为DateTime?
接受空值,我失去了ToString(string)
重载的定义。 我需要使用DateTime?
当我从一个可能具有空值的数据库中读取时 – 如果数据库中的字段具有空值,那么我也需要为变量赋值空值。
所以我有两个问题:
1)出于好奇,有没有人知道DateTime?
是否有原因DateTime?
不包含ToString(string)
的重载?
2)有人可以为我想要实现的目标提出另一种方法吗?
DateTime?
是Nullable
语法糖,这就是它没有ToString(format)
重载的原因。
但是,您可以使用Value
属性访问基础DateTime
结构。 但在此之前使用HasValue
检查,如果值存在。
MessageBox.Show(dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty)
您可以编写扩展方法,而不必每次都手动执行空检查。
public static string ToStringFormat(this DateTime? dt, string format) { if(dt.HasValue) return dt.Value.ToString(format); else return ""; }
并像这样使用它(使用你想要的任何字符串格式)
Console.WriteLine(myNullableDateTime.ToStringFormat("dd/MM/yyyy hh:mm:ss"));
你仍然可以使用
上述就是C#学习教程:没有DateTime?.ToString(string)重载?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
variableName.Value.ToString(customFormat);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/953478.html