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

查看:32
本文介绍了将 If 运算符的结果分配给 System.Nullable 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 If 运算符时 (http://msdn.microsoft.com/en-us/library/bb513985(v=VS.100).aspx) 为 System.Nullable 赋值strong> 对象,如果结果为 Nothing(空),则为该对象赋值 0.

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.

示例:

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

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

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.

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

If 运算符不会在其参数类型之间进行任何转换,它们都被同等对待 - 在您的情况下为 Integer.因此您的代码与

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?))

这篇关于将 If 运算符的结果分配给 System.Nullable 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆