条件三元运算符中 Nullable(Of ) 未设置为 Nothing

问题描述 投票:0回答:1

为什么我无法通过条件三元运算符将 Nothing 设置为 Nullable(Of Double) 但可以直接设置?

Dim d As Double? = Nothing
d = If(True, 0, Nothing)    ' result: d = 0
d = Nothing                 ' result: d = Nothing
d = If(False, 0, Nothing)   ' result: d = 0 Why?

编辑:这些工作(基于下面接受的答案):

d = If(False, 0, New Integer?)
d = If(False, CType(0, Double?), Nothing)
d = If(False, 0, CType(Nothing, Double?))
vb.net double nullable
1个回答
1
投票

Nothing
可以转换为很多类型,而不仅仅是
T?
。它可以愉快地转换为
Double
:

Function X() As Double
    Return Nothing ' result: 0.0
End Function

Integer
。这就是您在
Nothing
中使用的
If(X, 0, Nothing)
的含义,因为
If
需要第二个和第三个参数在类型上匹配:它将其视为类型
Integer
,因为这是
0
的类型。

显式指定其中一种类型为可空(

Integer?
Double?
都可以)让编译器弄清楚你想要什么:

d = If(False, CType(0, Double?), Nothing)
,或
d = If(False, 0, CType(Nothing, Double?))

© www.soinside.com 2019 - 2024. All rights reserved.