可空对象必须具有值vb

时间:2011-12-05 21:10:32

标签: vb.net nullable

我有一个更大的代码块,我在这个更简单的例子中重新创建了:

    Dim evalcheck As Boolean
    Dim aEntityId, bEntityId As Integer?
    Dim aCheckNumber, bCheckNumber As Integer?

    aEntityId = Nothing
    bEntityId = Nothing
    aCheckNumber = Nothing
    bCheckNumber = Nothing
    evalcheck = aEntityId = bEntityId And aCheckNumber = bCheckNumber

当我将Nothing与Nothing对进行比较时,我得到可空对象必须有一个值。

是否有快速修复eval部分 -

evalcheck = aEntityId = bEntityId And aCheckNumber = bCheckNumber

1 个答案:

答案 0 :(得分:0)

您应该使用括号来提高可读性。即使这样,比较也很难看。

If ((aEntityId IsNot Nothing And bEntityId IsNot Nothing) AndAlso (aEntityId = bEntityId)) Or (aEntityId Is Nothing And bEntityId Is Nothing) Then
    If ((aCheckNumber IsNot Nothing And bCheckNumber IsNot Nothing) AndAlso (aEntityId = bEntityId)) Or (aCheckNumber Is Nothing And bCheckNumber Is Nothing) Then
        evalcheck = True
    Else
        evalcheck = False
    End If
Else
    evalcheck = False
End If

我更喜欢这种方法

Private Function NullableIntsEqual(ByVal a As Integer?, ByVal b As Integer?) As Boolean
    If ((a IsNot Nothing And b IsNot Nothing) AndAlso (a = b)) Or (a Is Nothing And b Is Nothing) Then
        Return True
    Else
        Return False
    End If
End Function

您的evalcheck行变为

evalcheck = NullableIntsEqual(aEntityId, bEntityId) And NullableIntsEqual(aCheckNumber, bCheckNumber)