C# 如何从可空DateTime对象提取日期 解决CS1501报错
你遇到的报错是因为DateTime?(可空DateTime类型)本身的ToString方法没有接收格式参数的重载,只有无参版本,才会触发CS1501错误。你需要先访问可空对象的Value属性拿到底层的DateTime结构,再调用带格式参数的ToString方法,同时要注意判空避免空值异常。
常用实现方案
- C# 6及以上版本最简洁的写法,用null条件运算符自动判空:
// 如果DueDate为null,dueDate会被赋值为null string dueDate = siteRow.DueDate?.ToString(cultureInfo.DateTimeFormat.ShortDatePattern);
如果需要空值时返回默认字符串(比如空串),可以搭配null合并运算符:
string dueDate = siteRow.DueDate?.ToString(cultureInfo.DateTimeFormat.ShortDatePattern) ?? string.Empty;
- 低版本C#手动判空写法:
string dueDate = string.Empty; if (siteRow.DueDate.HasValue) { dueDate = siteRow.DueDate.Value.ToString(cultureInfo.DateTimeFormat.ShortDatePattern); }
内容的提问来源于stack exchange,提问作者Coder
相关产品推荐
相关产品推荐

