VB.NET - Nullable DateTime和Ternary运算符

时间:2010-11-15 23:29:29

标签: vb.net datetime nullable ternary-operator

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

方法1

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

方法2

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

当给出一个空字符串时,方法1将一个Null(Nothing)值赋给gauge.LastCalibrationDate,但方法2将它赋予DateTime.MinValue。

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

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

这正确地将Null(Nothing)从三元运算符赋予Nullable DateTime。

我错过了什么?谢谢!

2 个答案:

答案 0 :(得分:15)

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

  1. If三元运算符只能返回一种类型,在这种情况下是日期类型,而不是可以为空的日期类型
  2. VB.Net Nothing值实际上不是null,而是等同于指定类型的默认值,在这种情况下是日期,而不是可以为空的日期。因此,日期最小值。
  3. 我从此SO帖子中获得了此答案的大部分信息:Ternary operator VB vs C#: why resolves to integer and not integer?

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

答案 1 :(得分:15)

鲍勃麦克是正确的。特别注意他的第二点 - 在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)

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