代码之家  ›  专栏  ›  技术社区  ›  anonymous

VB.NET-可为空的日期时间和三元运算符

  •  8
  • anonymous  · 技术社区  · 14 年前

    我对VB.NET中的可空DateTime(VS 2010)有问题。

    方法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。

    我错过了什么?谢谢!

    2 回复  |  直到 14 年前
        1
  •  16
  •   Community CDub    8 年前

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

    1. 这个 If 三元运算符只能返回一种类型,在本例中是日期类型,而不是可为空的日期类型
    2. VB.Net Nothing 价值不是真的 null 但相当于指定类型的默认值,在本例中是日期,而不是可为空的日期。因此是日期最小值。

    我从这篇文章中得到了这个答案的大部分信息: Ternary operator VB vs C#: why resolves to integer and not integer?

    希望这能有所帮助,像乔尔·科霍恩这样的人能对这个问题有更多的了解。

        2
  •  16
  •   Ahmad Mageed    14 年前

    鲍勃·麦克是对的。要特别注意他的第二点——这不是C#的情况。

    你需要做的是武力 Nothing 将其强制转换为可为空的日期时间,如下所示:

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