在可以为空的DateTime对象上使用ToShortDateString()方法的一些问题,为什么?

And*_*ili 2 .net c# asp.net datetime

我有以下问题.

在课堂上我宣布:

vulnerabilityDetailsTable.AddCell(new PdfPCell(new Phrase(currentVuln.Published.ToString(), _fontNormale)) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 30, PaddingTop = 10 });
Run Code Online (Sandbox Code Playgroud)

而有趣的部分是:currentVuln.Published.ToString().这工作很好.

发布是一个声明为DateTime属性,这样:

public System.DateTime? Published { get; set; }
Run Code Online (Sandbox Code Playgroud)

问题是,在之前的方式中,currentVuln.Published.ToString()的打印值类似于18/07/2014 00:00:00(时间也包含在日期中).

我想只显示日期而不显示时间,所以我尝试使用类似的东西:

currentVuln.Published.ToShortDateString()
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我在Visual Studio中获取以下错误消息:

错误4'System.Nullable <System.DateTime>'不包含'ToShortDateString'的定义,并且没有可以找到接受类型'System.Nullable <System.DateTime>'的第一个参数的扩展方法'ToShortDateString'(是你吗?)缺少using指令或汇编引用?)C:\ Develop\EarlyWarning\public\Implementazione\Ver2\PdfReport\PdfVulnerability.cs 93 101 PdfReport

这似乎发生了,因为我的DateTime字段可以为空.

我错过了什么?我该如何解决这个问题?

Gra*_*ICA 12

你是对的,这是因为你的DateTime领域是可空的.

a的扩展方法DateTime不可用DateTime?,但要理解为什么,你必须意识到实际上没有DateTime?类.

最常见的,我们写使用可空类型?语法,如DateTime?,int?等如同上面一样.但是,这只是语法糖Nullable<DateTime>,Nullable<int>等等.

public Nullable<DateTime> Published { get; set; }
Run Code Online (Sandbox Code Playgroud)

所有那些明显不同的Nullable类型都来自一个包含您的类型的通用 Nullable<T>结构,并提供两个有用的属性:

  • HasValue (用于测试底层包装类型是否具有值),和
  • Value (用于访问该基础值,假设有一个)

检查以确保首先存在值,然后使用该Value属性访问基础类型(在本例中为a DateTime),以及通常可用于该类型的任何方法.

if (currentVuln.Published.HasValue)
{
    // not sure what you're doing with it, so I'll just assign it...

    var shortDate = currentVuln.Published.Value.ToShortDateString();
}
Run Code Online (Sandbox Code Playgroud)

  • @AndreaNobili发生这种情况的原因是可以为空的DateTime隐藏/封装其中的实际值,因此它没有`ToShortDateString()`函数. (2认同)