Nullable类型与内联如果不能一起工作? [英] Nullable type with inline if cannot work together?
问题描述
给出以下代码:
Dim widthStr As String = Nothing
此作品 - 宽度
已分配 Nothing
:
This works - width
is assigned Nothing
:
Dim width As Nullable(Of Double)
If widthStr Is Nothing Then
width = Nothing
Else
width = CDbl(widthStr)
End If
但是这不 - 宽度
变为 0.0
(虽然它似乎是逻辑上相同的代码):
But this does not - width
becomes 0.0
(although it seems to be logically identical code):
Dim width As Nullable(Of Double) = If(widthStr Is Nothing, Nothing, CDbl(widthStr))
为什么?有什么我可以做的吗?
Why? Is there anything I can do to make it work?
推荐答案
这一切都归结为表达式的类型分析。
This all comes down to type analysis of expressions.
Nothing
是VB.Net中的神奇野兽。它与C#中的默认(T)
大致相同。
Nothing
is a magical beast in VB.Net. It's approximately the same as default(T)
in C#.
因此,在尝试确定最佳类型时对于以下内容:
As such, when trying to determine the best type for the following:
If(widthStr Is Nothing, Nothing, CDbl(widthStr))
第三个参数类型为 Double
。第二个参数可转换为 Double
(因为 Nothing
可以返回值类型的默认值)。因此,返回值 If
的类型被确定为 Double
。
The third argument is of type Double
. The second argument is convertible to Double
(because Nothing
can return the default value of value types). As such, the type of the return value of If
is determined to be Double
.
只有在之后的那个类型分析结束时才会注意到该表达式所分配的变量的类型。并且 Double
可分配给 Double?
,不会发出任何警告。
Only after that piece of type analysis has concluded is any attention paid to the type of the variable to which this expression is being assigned. And Double
is assignable to Double?
without any warnings.
没有 clean 方法来使你的 If()
表达式符合您的预期。因为在VB.Net中没有相当于 null
的内容。您需要(至少)在的潜在结果的一侧或另一侧插入
强制类型分析看 DirectCast
(或等效物)> Double?
而不是 Double
。
There's no clean way to make your If()
expression work how you expected. Because there's no equivalent to null
in VB.Net. You'd need (at the least) to insert a DirectCast
(or equivalent) on one side or another of the potential results of the If
to force the type analysis to see Double?
rather than Double
.
这篇关于Nullable类型与内联如果不能一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!