gpt4 book ai didi

c# - 在可为空的 DateTime 对象上使用 ToShortDateString() 方法时出现一些问题,为什么?

转载 作者:行者123 更新时间:2023-11-30 18:54:41 27 4
gpt4 key购买 nike

我有以下问题。

在我声明的类中:

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

有趣的部分是:currentVuln.Published.ToString()。这工作正常。

Published 是一个声明为nullableDateTime 属性,以这种方式:

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

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

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

currentVuln.Published.ToShortDateString()

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

Error 4 'System.Nullable<System.DateTime>' does not contain a definition for 'ToShortDateString' and no extension method 'ToShortDateString' accepting a first argument of type 'System.Nullable<System.DateTime>' could be found (are you missing a using directive or an assembly reference?) C:\Develop\EarlyWarning\public\Implementazione\Ver2\PdfReport\PdfVulnerability.cs 93 101 PdfReport

这似乎是因为我的 DateTime 字段可以为空。

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

最佳答案

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

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

最常见的是,我们使用 ? 编写可空类型语法,如 DateTime? , int? ,等等,就像你上面所做的那样。但这只是syntactic sugar对于 Nullable<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();
}

对于 C# 6.0 及更高版本,您可以使用 null conditional而不是 .Value :

    var shortDate = currentVuln.Published?.ToShortDateString();

关于c# - 在可为空的 DateTime 对象上使用 ToShortDateString() 方法时出现一些问题,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25060876/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com