Visual Basic 中的可空类型推断——是否在某处记录了它并且可以使其更严格?

Nullable type inference in Visual Basic – is it documented somewhere and can it be made more strict?

i的结果:

Dim i As Integer? = If(True, Nothing, 3)

答案:0

如果你期望得到Nothing,你必须修改整型参数:

Dim i As Integer? = If(True, Nothing, New Nullable(3))

如您所见,从第 2 个和第 3 个参数推断的结果类型在 Nullable(Of T) 之前更喜欢 T。对我来说,逻辑上恰恰相反。

在哪里可以找到这些 inference/prioritization 类型规则(尤其是 Nullable 的规则)? 我查看了 type inference 的帮助,NullableIf,但我找不到任何东西。

偷看邻居:(很好地)拒绝编译等价物

int? i = true ? null : 3;

有错误

CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'

. But in the VB, even Option Infer Off+Option Strict On do not have any error-throwing effect, which could save programmer from unnoticed errors. Or is there a way to generate an error also in the ?

中,什么是安全的并且可以避免落入陷阱?

好的,现在我明白了。罪魁祸首是对 Nothing.

的解释

Nothing 更改为“true” null 导致正确的结果:

Dim i As Integer? = If(True, New Nullable(Of Integer), 3)

结果:i Is Nothing

所以可能的问题是 Nothing 似乎首先被编译器视为另一种类型(整数)的默认值而不是 null。改变它的隐含意义会有所帮助。无论如何,这是一个棘手的地方。 如果有人能找到这个记录,那就太好了。(我不坚持这个答案。)如果 VB 可以强制抛出错误,那就太好了或发生这种情况时发出警告,类似于 C#。


如在其他地方 comment 中所见,可以存在更好的表示法形式:

Dim i As Integer? = If(True, Integer?, 3)

不错!