2010-11-15 29 views
7

我在VB.NET(VS 2010)中遇到Nullable DateTime的问题。VB.NET - 可为空的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分配一个空(没有)值gauge.LastCalibrationDate但方法2为其分配DateTime.MinValue。

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

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

这正确地从一个三元运算符指定空(没有)为可空的DateTime。

我错过了什么?谢谢!

回答

13

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

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

我得到的大部分的此信息,答案从这个SO职位:Ternary operator VB vs C#: why resolves to integer and not integer?

希望这有助于和有人喜欢乔尔Coehoorn可以揭示主题更多的光线。

14

鲍勃麦是正确的。请特别注意他的第二点 - 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?()。后一种格式看起来有点奇怪,但它是有效的。

+2

+1不错的工作添加将产生所需结果的解决方法。 – 2010-11-16 16:02:23