为什么我的 Nullable(Of Int32) = 0 在我将它设置为 Nothing 之后?
Why is my Nullable(Of Int32) = 0 after I set it to Nothing?
我想我遗漏了一些关于可空类型的基本知识。希望这个例子能开辟新的理解,但至少,也许我们能让这件事正常工作。
在Class(对话框形式)中,我声明:
Property ProductStructureHeaderKey As Int32?
在另一个 Class 中,我声明了该对话框的一个实例并尝试使用此行设置 属性:
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))
当该行将 Nothing 分配给 属性 时,属性 等于 0。(然后,当我希望它传递 NULL 时,它将 0 传递给 DB。)
这不是我所期望的,我一直在寻找看起来我做事正确的代码(SO、MSDN 等),但很明显,我不是。那么,朋友们,我做错了什么?我如何使用 Nullable 类型来满足我的需求?
这是 C# 和 VB.NET 之间的区别之一。在VB.NET中,Nothing
不仅表示null
,还表示default
。因此,您将 Int32
的默认值分配给 属性 0。这是由 If
-operator 必须从两个值而不是 [=31] 推断类型引起的=] 您要分配的。
而是使用 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
或使用 new Nullable(Of Int32)
强制为空:
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, new Nullable(Of Int32), Int32.Parse(parentRow.Cells(1).Value))
进一步阅读:Why is there a difference in checking null against a value in VB.NET and C#?
我想我遗漏了一些关于可空类型的基本知识。希望这个例子能开辟新的理解,但至少,也许我们能让这件事正常工作。
在Class(对话框形式)中,我声明:
Property ProductStructureHeaderKey As Int32?
在另一个 Class 中,我声明了该对话框的一个实例并尝试使用此行设置 属性:
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))
当该行将 Nothing 分配给 属性 时,属性 等于 0。(然后,当我希望它传递 NULL 时,它将 0 传递给 DB。)
这不是我所期望的,我一直在寻找看起来我做事正确的代码(SO、MSDN 等),但很明显,我不是。那么,朋友们,我做错了什么?我如何使用 Nullable 类型来满足我的需求?
这是 C# 和 VB.NET 之间的区别之一。在VB.NET中,Nothing
不仅表示null
,还表示default
。因此,您将 Int32
的默认值分配给 属性 0。这是由 If
-operator 必须从两个值而不是 [=31] 推断类型引起的=] 您要分配的。
而是使用 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
或使用 new Nullable(Of Int32)
强制为空:
dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, new Nullable(Of Int32), Int32.Parse(parentRow.Cells(1).Value))
进一步阅读:Why is there a difference in checking null against a value in VB.NET and C#?