VB.NET - 可空 DateTime 和三元运算符

10

我在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

方法二

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 变量,写法正确。

我还有什么遗漏的吗?谢谢!


请问您能否在您的代码中添加gauge.LastCalibrationData的定义? - schlebe
2个回答

18

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


3
做得不错,加入了解决方法可以得到所需的结果。 - Bob Mc

17

我承认我不是这方面的专家,但显然这源自以下两点:

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

我从这篇SO帖子中获得了大部分答案:Ternary operator VB vs C#: why resolves to integer and not integer?

希望这可以帮助你,并且像Joel Coehoorn这样的人可以更好地阐明这个主题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接