VB.NET - Nullable DateTime和Ternary运算符

ano*_*ous 9 vb.net datetime nullable ternary-operator

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

方法1

If String.IsNullOrEmpty(LastCalibrationDateTextBox.Text) Then
    gauge.LastCalibrationDate = Nothing
Else
    gauge.LastCalibrationDate = DateTime.Parse(LastCalibrationDateTextBox.Text)
End If
Run Code Online (Sandbox Code Playgroud)

方法2

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), Nothing, DateTime.Parse(LastCalibrationDateTextBox.Text))
Run Code Online (Sandbox Code Playgroud)

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

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

LastCalibrationDate = If(IsDBNull(dr("LastCalibrationDate")), Nothing, dr("LastCalibrationDate"))
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?谢谢!

Ahm*_*eed 16

Bob Mc是对的.特别注意他的第二点 - 在C#中并非如此.

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

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), CType(Nothing, DateTime?), DateTime.Parse(LastCalibrationDateTextBox.Text))
Run Code Online (Sandbox Code Playgroud)

这是一个演示代码段:

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)
Run Code Online (Sandbox Code Playgroud)

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

  • +1好的工作添加将产生所需结果的变通方法. (3认同)

Bob*_* Mc 15

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

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

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

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