vb.net - .NET 三元运算符和类型转换的问题

标签 vb.net ternary-operator

我有一个三元表达式,用于检查Object是否为DBNull.Value,如果True则返回Nothing code> else if False 返回转换为该 ObjectDate 类型的值。然而,由于某种奇怪的原因,我的三元表达式设置的可空 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/

相关文章:

.net - 通用列表匹配任何值

c# - 在 C# 中具有 bool 条件的三元

vb.net - 使用串口转 USB 开关控制程序

c# - 如果 "using"有异常会自动关闭

c# - 使用自定义编译器进行枚举的自定义三元运算符

java - 如何在 super 关键字内使用具有多个条件的三元运算符?

javascript - 需要澄清使用 0 和三元运算符

dart - 如何在 flutter dart 中使用具有多个条件的三元运算符?

vb.net - 通过显示点而不是文件路径的某些部分,将完整的文件路径安装在一行标签中 Vb.Net

asp.net - Crystal 在 ASP.NET vb 中报告错误,无需 Crystal 报告