vb.net - 将 Nullable 属性默认值设置为 Nothing 无法正常工作

标签 vb.net nullable short-circuiting

我有一个属性,其类型是 IntegerNullable 和默认值 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)

最佳答案

这是因为您正在使用 Option Strict Off 编译代码。

如果您使用Option Strict On 编译您的代码,编译器会给您一个错误,告诉您它不能从String 转换为整数?,避免在运行时出现此类意外。


在 VB.NET 中使用 properties/三元运算符/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)

关于vb.net - 将 Nullable 属性默认值设置为 Nothing 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11445303/

相关文章:

mysql - mysql 中的 vb.net 组合框值

.net - 如何在 VB.NET 中替换 List(Of String) 中的项目?

Typescript - 将 null 分配给变量

c# - 使用 LINQ 将 DateTime?[] 中的 null 替换为 DateTime.MaxValue

PHP短路懒人测评,php.net手册在哪?

javascript - 有人能解释一下为什么 "operator precedence"适用于 javaScript 中的 "||"、 "&&"等逻辑运算符吗

vb.net - 如何根据 vb.net 中的内容设置 datagridview 的行高

vb.net - 如何避免 <string xmlns ="http://schemas.microsoft.com/2003/10/Serialization/">?

c# - 如何将 DateTime.TryParse 与 Nullable<DateTime> 一起使用?

python - 在 Python 中处理时,如何确保任意函数调用列表不会急切地评估超过短路点?