将If运算符的结果分配给System.Nullable类型(Assigning result of If operator to System.Nullable type)

编程入门 行业动态 更新时间:2024-10-10 21:24:23
将If运算符的结果分配给System.Nullable类型(Assigning result of If operator to System.Nullable type)

当使用If运算符( http://msdn.microsoft.com/zh-cn/library/bb513985(v=VS.100).aspx )将值分配给System.Nullable对象时,如果结果为Nothing( null),则将0分配给该对象。

例:

'Expected value is null (Nothing). Actual value assigned is 0. Dim x As System.Nullable(Of Integer) = If(1 = 0, 1, Nothing)

如果x是一个可为空的类型,为什么它被分配了默认的整数类型0.它不应该得到一个值为null吗?

When using the If operator (http://msdn.microsoft.com/en-us/library/bb513985(v=VS.100).aspx) to assign a value to a System.Nullable object, if the result is Nothing (null), then 0 is assigned to the object.

Example:

'Expected value is null (Nothing). Actual value assigned is 0. Dim x As System.Nullable(Of Integer) = If(1 = 0, 1, Nothing)

If x is a nullable type, why is it being assigned the default integer type of 0. Shouldn't it receive a value of null?

最满意答案

值类型上下文中的Nothing不会解析为该类型的默认值。 对于一个整数,这只是0 。

If运算符在它的参数类型之间没有进行任何转换,它们都被平等地对待 - 在你的情况下是Integer 。 因此你的代码和

Dim x As Integer? = If(1 = 0, 1, 0)

为了使结果可以为空,你需要明确的类型。

Dim x As Integer? = If(1 = 0, 1, CType(Nothing, Integer?))

Nothing in the context of a value type resolves to the default value for that type. For an integer, this is just 0.

The If operator does not do any conversions between its argument types, they are all treated equally – as Integer in your case. Hence your code is the same as

Dim x As Integer? = If(1 = 0, 1, 0)

To make the result nullable, you need to make the types explicit.

Dim x As Integer? = If(1 = 0, 1, CType(Nothing, Integer?))

更多推荐

本文发布于:2023-08-02 10:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372713.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   类型   Nullable   System   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!