3

我有一个类型为默认值的属性,Nullable如下Integer所示Nothing

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)

4

1 回答 1

2

这是因为您正在使用Option Strict Off.

如果你用 编译你的代码Option Strict On,编译器会给你一个错误,告诉你它不能从Stringto转换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)
于 2012-07-12T06:38:23.000 回答