为什么我将 Nullable(Of Int32) = 0 设置为 Nothing 后?

clw*_*eks 2 vb.net nullable

我认为我遗漏了一些关于可空类型的基本知识。希望这个例子能够开启新的理解,但至少,也许我们可以让这件事顺利进行。

在类(对话框形式)中,我声明:

Property ProductStructureHeaderKey As Int32?
Run Code Online (Sandbox Code Playgroud)

在另一个类中,我声明该对话框的一个实例,并尝试使用以下行设置该属性:

    dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))
Run Code Online (Sandbox Code Playgroud)

当该行将 Nothing 分配给属性时,该属性等于 0。(然后,当我希望它传递 NULL 时,它会将 0 传递给数据库。)

这不是我所期望的,我一直在寻找代码(SO、MSDN 等),看起来我做的事情是正确的,但显然,我没有。那么,朋友们,我做错了什么?如何使用可空类型来满足我的需求?

Tim*_*ter 5

这是 C# 和 VB.NET 之间的区别之一。在 VB.NET 中Nothing不仅意味着null而且还意味着default. Int32因此,您将0 指定给属性的默认值。这是由If- 运算符引起的,该操作符必须从两个值而不是从您要分配的属性推断类型。

相反,使用If...Else

If parentRow.Cells(1).Value Is Nothing Then
    dr.ProductStructureHeaderKey = Nothing ' Now it's not 0 but Nothing
Else
    dr.ProductStructureHeaderKey = Int32.Parse(parentRow.Cells(1).Value)
End If
Run Code Online (Sandbox Code Playgroud)

或者使用以下命令强制可为空new Nullable(Of Int32)

dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, new Nullable(Of Int32), Int32.Parse(parentRow.Cells(1).Value))
Run Code Online (Sandbox Code Playgroud)

进一步阅读:为什么在 VB.NET 和 C# 中检查 null 值时存在差异?