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

问题描述 投票:2回答:3

我有以下问题。

在课堂上我宣布:

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

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

发布是一个声明为可为空的DateTime属性,以这种方式:

public System.DateTime? Published { get; set; }

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

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

currentVuln.Published.ToShortDateString()

但它不起作用,我在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字段可以为空。

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

c# asp.net .net datetime
3个回答
11
投票

你是对的,这是因为你的DateTime字段可以为空。

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

最常见的是,我们使用?语法编写可空类型,如DateTime?int?等,如上所述。但这只是syntactic sugarNullable<DateTime>等的Nullable<int>

public Nullable<DateTime> Published { get; set; }

所有那些显然是独立的Nullable类型来自单个generic Nullable<T> struct,它包裹你的类型并提供两个有用的属性:

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

检查以确保首先存在值,然后使用Value属性访问基础类型(在本例中为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();
}

2
投票

值类型Nullable<>封装了另一个值类型的值以及布尔值hasValue

这种类型的Nullable<>从其最终基类string ToString()继承了System.Object方法。它还使用新实现覆盖此方法。如果""hasValue,则新实现返回false,如果.ToString()System.Object,则返回它从hasValue获取的封装值(也继承true)的字符串。

这就是您现有代码合法的原因。

Nullable<>类型没有任何方法ToShortDateString。您必须通过Value属性转到封装值。因此,而不是非法:

currentVuln.Published.ToShortDateString()    /* error */

你会需要

currentVuln.Published.HasValue ? currentVuln.Published.Value.ToShortDateString() : ""

或者,等效地

currentVuln.Published != null ? currentVuln.Published.Value.ToShortDateString() : ""

(两者都在运行时相同)。您可以将字符串""更改为其他内容,如"never""not published",如果您愿意的话。

如果Published属性(它的get访问器)被调用两次可能是一个问题,你需要在某处取出一个临时变量,var published = currentVuln.Published;,并使用:published.HasValue ? published.Value.ToShortDateString() : ""


2
投票

以防其他人遇到这个帖子。您可以使用.value.ToShortDateString()。这将解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.