I am trying to understand why the two code samples behave differently. I always believed the If() function to mimic the If language fea开发者_JS百科ture. 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
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.
Dim i As Integer = Nothing 'results in i being set to 0
To get what you want with If() try the following:
Dim pcFilter2 As Integer? = If(Not String.IsNullOrWhiteSpace(PC.SelectedValue),
New Integer?(CInt(PC.SelectedValue)),
Nothing)
精彩评论