【问题标题】:Issue With .NET Ternary Operator and Type Conversions.NET 三元运算符和类型转换的问题
【发布时间】:2019-03-26 15:59:45
【问题描述】:

我有一个三元表达式,它检查Object 是否为DBNull.Value,如果True 返回Nothing,否则如果False 返回转换为Date 类型的值Object .然而,由于某种奇怪的原因,我的可空变量DateTime 被三元表达式设置为神秘地设置为'1/1/0001 12:00:00 AM',即使Object 肯定是DBNull.Value。其他人可以重现这种行为吗?如果是这样,为什么会发生?

奇怪的是,我已将此表达式更改为常规的旧 if 和 else 块,但我根本没有得到这种行为。因此,它必须与三元语句有关。

Module Module1

Sub Main()
    Dim dt As New DataTable
    dt.Columns.Add(New DataColumn("DateColumn", GetType(String)))
    dt.Rows.Add()
    Dim testDate = dt(0).Item(0)
    Dim setDate As DateTime? = Nothing
    'Doesn't work
    setDate = If(testDate Is DBNull.Value, Nothing, CDate(testDate))
    'Works
    'If testDate Is DBNull.Value Then
    '    setDate = Nothing
    'Else
    '    setDate = CDate(testDate)
    'End If
    'Also works
    'setDate = If(testDate Is DBNull.Value, Nothing, CType(testDate, DateTime?))
    'This works too
    'setDate = If(testDate Is DBNull.Value, Nothing, testDate)
    'Working
    'setDate = IIf(testDate Is DBNull.Value, Nothing, testDate)
    If setDate IsNot Nothing Then
        Console.WriteLine("Why does setDate = '" & setDate.ToString & "' ?!")
    End If
    Console.ReadKey()
End Sub

End Module

我想使用三元语句,因为它的代码更少。

【问题讨论】:

  • 我认为VB中的三元运算符是IIF,而不是IF。也许这就是问题所在?
  • 您可以同时使用这两种方法,但在这个 IIF 的特定示例中,问题是 true 和 false 表达式都被评估,如果 testDateDBNull.Value,则会引发异常。实际上,如果我删除对 CDate 的调用,两者都会按预期工作。
  • 一个基本的要求是false和true的部分必须有相同的类型,这样表达式的类型是明确的。这是为 CDate() 确定的,它除了将 Nothing 转换为 Date 之外什么也做不了。正如您所发现的那样,这是可能的。
  • 啊,我明白了。因为我使用的是 CDate,所以三元表达式的返回类型将始终是 Date 类型,它不能为空。这是正确的吗?

标签: vb.net ternary-operator


【解决方案1】:

原因是 VB 将 If 运算符的返回类型推断为 Date,因为这是 CDate 返回的。 Nothing 关键字可以转换为不可为空的Date 对象,因为在VB 中Nothing 也意味着“默认”,而Date 的默认值为1/1/0001 12:00:00 AM。要解决此问题,您必须确保至少有一个参数明确为 DateTime?

例如,这会起作用:

setDate = If(testDate Is DBNull.Value, New DateTime?, CDate(testDate))

【讨论】:

  • 谢谢,我没想到会这样做。我觉得我今天学到了一些东西。
猜你喜欢
  • 2012-12-15
  • 2011-10-12
  • 2021-10-02
  • 1970-01-01
  • 2011-10-24
  • 2011-12-17
  • 2020-07-18
  • 1970-01-01
  • 2017-01-20
相关资源
最近更新 更多