【问题标题】:VB.NET - Nullable DateTime and Ternary OperatorVB.NET - 可空日期时间和三元运算符
【发布时间】:2011-05-10 13:06:15
【问题描述】:

我在 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(无)正确分配给 Nullable DateTime。

我错过了什么?谢谢!

【问题讨论】:

  • 请您添加您在代码中使用的 gauge.LastCalibrationData 定义吗?

标签: vb.net datetime nullable ternary-operator


【解决方案1】:

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

您需要做的是将 Nothing 强制转换为可为空的 DateTime,方法如下:

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

这里有一个sn-p来演示:

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?()。后一种格式看起来有点奇怪,但它是有效的。

【讨论】:

  • +1 添加能产生预期结果的变通办法,做得很好。
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2013-09-20
    • 2023-04-04
    • 2021-10-06
    • 2010-10-09
    • 2013-06-28
    • 1970-01-01
    • 2014-08-16
    • 2023-03-07
    • 2021-04-08
    相关资源
    最近更新 更多