10

我在 VB.NET(VS 2010)中遇到了 Nullable DateTime 的问题。

方法一

If String.IsNullOrEmpty(LastCalibrationDateTextBox.Text) Then
    gauge.LastCalibrationDate = Nothing
Else
    gauge.LastCalibrationDate = DateTime.Parse(LastCalibrationDateTextBox.Text)
End If

方法二

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), Nothing, DateTime.Parse(LastCalibrationDateTextBox.Text))

当给定一个空字符串时,方法 1 将 Null(无)值分配给 gauge.LastCalibrationDate,但方法 2 为其分配 DateTime.MinValue。

在我的代码的其他地方,我有:

LastCalibrationDate = If(IsDBNull(dr("LastCalibrationDate")), Nothing, dr("LastCalibrationDate"))

这正确地将 Null (Nothing) 从三元运算符分配给 Nullable DateTime。

我错过了什么?谢谢!

4

2 回答 2

17

鲍勃麦克是正确的。请特别注意他的第二点 - C# 中不是这种情况。

您需要做的是Nothing通过强制转换为可为空的 DateTime ,如下所示:

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), CType(Nothing, DateTime?), DateTime.Parse(LastCalibrationDateTextBox.Text))

这是一个片段来演示:

Dim myDate As DateTime?
' try with the empty string, then try with DateTime.Now.ToString '
Dim input = ""
myDate = If(String.IsNullOrEmpty(input), CType(Nothing, DateTime?), DateTime.Parse(input))
Console.WriteLine(myDate)

除了强制转换,您还可以声明一个新的 nullable:New Nullable(Of DateTime)New DateTime?(). 后一种格式看起来有点奇怪,但它是有效的。

于 2010-11-16T03:45:05.700 回答
16

我承认我不是这方面的专家,但显然它源于两件事:

  1. If三元运算符只能返回一种类型,在这种情况下是日期类型,而不是可为空的日期类型
  2. VB.NetNothing值实际上并不null等同于指定类型的默认值,在本例中为日期,而不是可为空的日期。因此日期最小值。

我从这个 SO 帖子中获得了这个答案的大部分信息:三元运算符 VB 与 C#:为什么解析为整数而不是整数?

希望这会有所帮助,并且像 Joel Coehoorn 这样的人可以对这个主题有更多的了解。

于 2010-11-16T01:01:46.300 回答