If() 函数中可空整数的默认值不同
我试图理解为什么两个代码示例的行为不同。我一直相信 If() 函数模仿了 If 语言功能。或者我正在寻找导致此问题的 Nullable(Of Integer) 行为?
示例 #1:
If Not String.IsNullOrWhiteSpace(PC.SelectedValue) Then
Dim pcFilter1 As Integer? = CInt(PC.SelectedValue)
Else
Dim pcFilter1 As Integer? = Nothing
End If
示例 #2:
Dim pcFilter2 As Integer? = If(Not String.IsNullOrWhiteSpace(PC.SelectedValue),
CInt(PC.SelectedValue),
Nothing)
结果:
pcFilter1 = 无
pcFilter2 = 0
I am trying to understand why the two code samples behave differently. I always believed the If() function to mimic the If language feature. Or am I looking at a behavior of Nullable(Of Integer) that is causing this?
Sample #1:
If Not String.IsNullOrWhiteSpace(PC.SelectedValue) Then
Dim pcFilter1 As Integer? = CInt(PC.SelectedValue)
Else
Dim pcFilter1 As Integer? = Nothing
End If
Sample #2:
Dim pcFilter2 As Integer? = If(Not String.IsNullOrWhiteSpace(PC.SelectedValue),
CInt(PC.SelectedValue),
Nothing)
Result:
pcFilter1 = Nothing
pcFilter2 = 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在示例 #2 中,您的 CInt 强制转换导致了问题。 If() 构造尝试确定第二个和第三个参数的公共类型。将第二个参数视为整数,然后将 Nothing 转换为整数,由于 VB 的魔法转换,结果为 0。例如,
要使用 If() 获得所需的内容,请尝试以下操作:
In sample #2, your CInt cast is causing the problem. The If() construct tries to determine a common type for the 2nd and 3rd parameters. Seeing the 2nd parameter as an integer it then converts Nothing into an integer, which due to VBs magic casting results in 0. e.g.
To get what you want with If() try the following: