【发布时间】: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 表达式都被评估,如果
testDate是DBNull.Value,则会引发异常。实际上,如果我删除对CDate的调用,两者都会按预期工作。 -
一个基本的要求是false和true的部分必须有相同的类型,这样表达式的类型是明确的。这是为 CDate() 确定的,它除了将 Nothing 转换为 Date 之外什么也做不了。正如您所发现的那样,这是可能的。
-
啊,我明白了。因为我使用的是 CDate,所以三元表达式的返回类型将始终是
Date类型,它不能为空。这是正确的吗?