将Nullable Integer设置为包含Nothing的字符串会产生0

Bri*_*Kay 3 .net vb.net nullable

我一直在从可空整数的一些意外行为中拉出我的头发.

  • 如果我设置IntegerNothing,它会变得Nothing如预期的那样.
  • 如果我设置Integer?StringNothing,它变成0!

当然,我得到这个我是否显式转换StringInteger?或没有.

我意识到我可以很容易地解决这个问题,但我想知道我错过了什么.

    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it's 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing. 
Run Code Online (Sandbox Code Playgroud)

编辑:以前我把我的代码放在这里,所以没有明确的转换Integer?,每个人似乎都被这个混淆/困惑.Option Strict On有很多建议会抓住这类东西.然而,这实际上是字符串到整数转换规则的一个怪癖,它早于可空类型,但仍会影响它们.

Jar*_*Par 6

之所以如此与VB.Net转换规则有关.该String类型与之不兼容,Integer?因此发生转换.中间步骤虽然转换StringInteger.VB.Net转换规则将a Nothing或empty String转换为Integer值0.这可以在没有nullables的情况下再现

Dim local1 As String = Nothing
Dim local2 As Integer = local1 ' It's 0
Run Code Online (Sandbox Code Playgroud)

然后,相同的转换将Integer值0 转换为Integer?维持该Integer值的类型.