错误?如果您通过三元运算符将值分配给可为空的整数,则该值不能为null [英] Bug?? If you assign a value to a nullable integer via a ternary operator, it can't become null
问题描述
dim val1 As Integer? = If(5 > 2, Nothing, 43)
' val1 = 0
dim val1 As Integer? = If(5 > 2, Nothing, Nothing)
' val1 = Nothing
什么给?
推荐答案
问题是没事$ VB.NET中的c $ c>的工作方式不同于C#中的
null
。在值类型的上下文中使用 Nothing
时(例如 Integer
),它表示该类型的默认值。在这种情况下,该值为0。
The problem is that Nothing
in VB.NET works differently than, for example, null
in C#. When Nothing
is used in the context of a value type (such as Integer
) it represents the default value of that type. In this case, that's 0.
在您的第一个示例中,三元运算符的两个分支都是有效的 Integer
值。
In your first example, both branches of the ternary operator are valid Integer
values. The true branch represents 0 and the false branch represents 43.
在第二个示例中,三元运算符的两个分支都不是有效的 Integer code>值,从而迫使VB.NET编译器假定整体运算符返回
Object
,而不是 Integer
。
In the second example, neither branch of the ternary operator is a valid Integer
value, thus forcing the VB.NET compiler to assume that the overall operator returns Object
, not Integer
.
要使第一个示例按您的预期方式工作,您需要向编译器明确说明三元运算符应解析为 Integer?
,而不是 Integer
或 Object
。您可以这样操作:
To make the first example work the way you intend, you need to make it clear to the compiler that the ternary operator should resolve to an Integer?
, not an Integer
or an Object
. You can do so like this:
dim val1 As Integer? = If(5 > 2, Nothing, New Integer?(43))
通过明确地使操作符的错误分支为 Integer?
,则真正分支中的 Nothing
将代表空值,而不是默认为整数
值。
By explicitly making the false branch of the operator an Integer?
, the Nothing
in the true branch will represent the null value, instead of the default Integer
value.
这篇关于错误?如果您通过三元运算符将值分配给可为空的整数,则该值不能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!