为什么我无法通过条件三元运算符将 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?))
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?))