【问题标题】:Why is my Nullable(Of Int32) = 0 after I set it to Nothing?为什么我将 Nullable(Of Int32) = 0 设置为 Nothing 后?
【发布时间】:2015-09-12 05:20:43
【问题描述】:

我认为我缺少一些关于可空类型的基本知识。希望这个例子能带来新的理解,但至少,也许我们可以让这件事正常工作。

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

Property ProductStructureHeaderKey As Int32?

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

    dr.ProductStructureHeaderKey = If(parentRow.Cells(1).Value Is Nothing, Nothing, Int32.Parse(parentRow.Cells(1).Value))

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

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

【问题讨论】:

  • DBNullNothing 不一样;看看应该通过DBNull 的“稍后”部分可能会有所帮助
  • 我在其他地方有处理 Nothing 到 NULL 转换的代码,问题确实是让这个 Nullable 设置为 Nothing。但是蒂姆的回答把我引向了我的愚蠢错误。

标签: vb.net nullable


【解决方案1】:

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

改为使用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#?

【讨论】:

  • Arg!除非我遗漏了什么,否则我实际上应该使用 = If(parentRow.Cells(1).Value, Nothing) 我一直忘记使用三部分 if() 的这一复杂情况——太令人沮丧了。
  • 我不知道parentRow是什么。
  • 仅当 parentRow.Cells(1).Value 返回 Nullable(Of Int32) 时,否则它不会在 Option Strict On 下编译。它必须隐式转换为Int32?
  • 哦,我明白了。当有一个值时,它是一个字符串,但它来自一个 SQL Int,所以我知道它要么总是要解析,要么什么都没有。所以,是的,你的new Nullable(Of Int32) 正是我所需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多