You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:09:00