我有一个三元表达式,用于检查Object
是否为DBNull.Value
,如果True
则返回Nothing
code> else if False
返回转换为该 Object
的 Date
类型的值。然而,由于某种奇怪的原因,我的三元表达式设置的可空 DateTime
变量甚至被神秘地设置为 '1/1/0001 12:00:00 AM'
尽管 Object
肯定是一个 DBNull.Value
。其他人可以重现这种行为吗?如果是这样,为什么会发生这种情况?
奇怪的是,我已将此表达式更改为常规旧的 if 和 else block ,但我根本没有得到这种行为。所以,这一定与三元语句有关。
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 将 If
运算符的返回类型推断为 Date
,因为这就是 CDate 返回的类型。 Nothing
关键字可以转换为不可为 null 的 Date
对象,因为 Nothing 在 VB 中也表示“默认”,而 Date 的默认值为 1/1/0001 12:00:00 上午
。要解决此问题,您必须确保至少有一个参数明确是 DateTime?
。
例如,这可以工作:
setDate = If(testDate Is DBNull.Value, New DateTime?, CDate(testDate))
关于vb.net - .NET 三元运算符和类型转换的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361437/