2012-07-12 47 views
3

我有一個屬性,該屬性類型是Integer一個默認值NothingNullable,如下所示:設置可爲空屬性默認值沒有如所期望不工作

Property TestId As Integer? = Nothing 

以下代碼評估屬性TestId爲Nothing(如想)

Dim test As RadTreeNode = rtvDefinitionCreate.FindNodeByValue(DefinitionHeaderEnum.Test) 
If test Is Nothing Then 
    definition.TestId = Nothing 
Else 
    definition.TestId = test.Nodes(0).Value 
End If 

但下面的代碼的計算結果爲0(默認值Integer,是Integer?與默認值即使當Nothing

Dim test As RadTreeNode = rtvDefinitionCreate.FindNodeByValue(DefinitionHeaderEnum.Test) 
definition.TestId = If(IsNothing(test), Nothing, test.Nodes(0).Value) 

上述代碼有什麼問題?任何幫助?

(稍後在代碼中調用屬性時,該屬性具有0)

回答

2

這是因爲你編譯你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

我認爲'因爲如果運營商不從沒有自動擴大轉換爲0(類型'test.Nodes選項嚴格On'不幫助這裏(0 ).Value') - 但解決方案應該工作! – 2012-07-12 06:46:09

+0

@PaulB。 'Option Strict On'在這裏將有助於解決編譯錯誤,突出問題。 – sloth 2012-07-12 06:52:06

+0

對我來說'Dim i Integer? = If(True,Nothing,1)'不會導致編譯錯誤,但將Nothing轉換爲0,然後將0轉換爲可空的0. – 2012-07-12 07:05:34