這是因爲你編譯你Option Strict Off
編碼。
如果您要用Option Strict On
編譯您的代碼,編譯器會給您一個錯誤,告訴您它不能從String
轉換爲Integer?
,避免在運行時出現這樣的驚喜。
這是一個在古怪VB.NET使用properties
/ternary operator
/option strict off
時。
考慮下面的代碼:
Class Test
Property NullableProperty As Integer? = Nothing
Public NullableField As Integer? = Nothing
End Class
Sub Main()
' Setting the Property directly will lest the ternary operator evaluate to zero
Dim b = New Test() With {.NullableProperty = If(True, Nothing, "123")}
b.NullableProperty = If(True, Nothing, "123")
' Setting the Property with reflection or setting a local variable
' or a public field lets the ternary operator evaluate to Nothing
Dim localNullable As Integer? = If(True, Nothing, "123")
Dim implicitLocal = If(True, Nothing, "123")
b.NullableField = If(True, Nothing, "123")
b.GetType().GetMethod("set_NullableProperty").Invoke(b, New Object() {If(True, Nothing, "123")})
b.GetType().GetProperty("NullableProperty").SetValue(b, If(True, Nothing, "123"), Nothing)
End Sub
另一個區別考慮:
Dim localNullable As Integer? = If(True, Nothing, "123")
將評估爲Nothing
但
Dim localNullable As Integer? = If(SomeNonConstantCondition, Nothing, "123")
將評估爲0
您可以創建一個擴展方法來爲您執行討厭的工作。
<Extension()>
Function TakeAs(Of T, R)(obj As T, selector As Func(Of T, R)) As R
If obj Is Nothing Then
Return Nothing
End If
Return selector(obj)
End Function
,並調用它像
definition.TestId = test.TakeAs(Of Int32?)(Function(o) o.Nodes(0).Value)
我認爲'因爲如果運營商不從沒有自動擴大轉換爲0(類型'test.Nodes選項嚴格On'不幫助這裏(0 ).Value') - 但解決方案應該工作! – 2012-07-12 06:46:09
@PaulB。 'Option Strict On'在這裏將有助於解決編譯錯誤,突出問題。 – sloth 2012-07-12 06:52:06
對我來說'Dim i Integer? = If(True,Nothing,1)'不會導致編譯錯誤,但將Nothing轉換爲0,然後將0轉換爲可空的0. – 2012-07-12 07:05:34