Nullable类型与内联如果不能一起工作?

Neo*_*isk 6 vb.net if-statement nullable

给出以下代码:

Dim widthStr As String = Nothing
Run Code Online (Sandbox Code Playgroud)

这项工作 - width分配Nothing:

Dim width As Nullable(Of Double)
If widthStr Is Nothing Then
  width = Nothing
Else
  width = CDbl(widthStr)
End If
Run Code Online (Sandbox Code Playgroud)

但这不会 - width变成0.0(虽然它似乎是逻辑上相同的代码):

Dim width As Nullable(Of Double) = If(widthStr Is Nothing, Nothing, CDbl(widthStr))
Run Code Online (Sandbox Code Playgroud)

为什么?有什么办法可以让它发挥作用吗?

Mar*_*urd 11

除了Damien的答案之外,干净的方法是使用Nothing,New Double?而是:

Dim width As Double? = If(widthStr Is Nothing, New Double?, CDbl(widthStr))
Run Code Online (Sandbox Code Playgroud)

现在If表达式的类型是正确的,这可以简化为:

Dim width = If(widthStr Is Nothing, New Double?, CDbl(widthStr))
Run Code Online (Sandbox Code Playgroud)


Dam*_*ver 5

所有这些都归结为表达式的类型分析。

Nothing在VB.Net中是一个神奇的野兽。它与default(T)C#大致相同。

因此,在尝试确定以下各项的最佳类型时:

If(widthStr Is Nothing, Nothing, CDbl(widthStr))
Run Code Online (Sandbox Code Playgroud)

第三个参数是类型Double。第二个参数可以转换为Double(因为Nothing可以返回值类型的默认值)。这样,返回值的If类型确定为Double

只有在完成该类型分析之后,才会注意将表达式分配给该变量的类型。并且Double可分配给Double?任何警告。


没有一种干净的方法可以使您的If()表情按预期工作。因为null在VB.Net中没有等效项。您(至少)需要在的DirectCast潜在结果的一侧或另一侧插入一个(或等效项),If以强制类型分析查看Double?而不是Double