3

我正在寻找验证一个DateTime变量以确保它在 UI 上不是空白的。字符串等效检查将是String.IsNullOrEmpty(),但我将如何处理我的DateTime变量?

4

2 回答 2

5

DateTime是一个值类型,所以它不能为空。要检查DateTime变量是否具有默认值(全为 0),您可以将其与new DateTime()或进行比较default(DateTime)

另一种选择是使用DateTime?而不是DateTime用户输入和检查HasValue属性。

于 2015-10-20T22:22:27.607 回答
2

要在 C# 中检查 aDateTime是否为空,您必须首先确保 DateTime 可以为空。

// DateTime? means it is nullable
var DateTime? date = null;

// .HasValue only exists if DateTime is nullable
if(date.HasValue)
    Console.WriteLine("date has a value");
else
    Console.WriteLine("date is null");

如果您DateTime的不可为空,请将其设为可空(除非您绝对确定 in 永远不会为空)。您不想走上为您的 DateTimes 分配“无效”值的道路。以我的经验,这会产生令人困惑的错误/代码。

于 2019-05-22T20:14:22.583 回答