比较可空枚举 (vb)

Compare Nullable Enum (vb)

我已经编写了以下代码来执行此操作,但是有没有更优雅的方法?

我有 2 个可为 null 的枚举。我想将它们相互比较,其中一个或两个可以为空。我必须分别测试相等性和空条件测试。有没有更好的方法?

Private Class a
    Public Enum MyColour
        Red
        Blue
    End Enum
    Public Property OriginalColour As MyColour?
    Public Property NewColour As MyColour?

    Public ReadOnly Property HasColourChanged As Boolean
        Get
            If (OriginalColour.HasValue And NewColour.HasValue) Then  'Both have values so test
                'Test if the values are the same
                If OriginalColour.Value = NewColour.Value Then
                    Return False
                Else
                    Return True
                End If
            End If

            'Either one or both values are null
            If OriginalColour.HasValue Xor NewColour.HasValue Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property
End Class

你只在一个条件下 return 为假,因此让你的 属性 return 默认为真,只有当你的条件满足时才 return 为假,即这样您就不必检查 return 是否为真。所以imo你不需要那么多条件,以下就足够了

Public ReadOnly Property HasColourChanged As Boolean
    Get
        If (OriginalColour.HasValue And NewColour.HasValue) Then  'Both have values so test
            'Test if the values are the same
            If OriginalColour.Value = NewColour.Value Then
                Return False                
        End If

        Return True
    End Get
End Property

我不确定这会增加可读性,但我相信您可以使用短路 AndAlso 运算符来缩写此代码以避免潜在的不必要的 RHS 检查,并且还可以使用条件运算符:

Public ReadOnly Property HasColourChanged As Boolean
    Get
        Return If (OriginalColour.HasValue AndAlso NewColour.HasValue, _
                   Not(OriginalColour.Value = NewColour.Value), _
                   OriginalColour.HasValue Xor NewColour.HasValue)      
    End Get
End Property

我测试了以下内容:

Dim test as New a
test.OriginalColour = MyColour.Red
test.NewColour = MyColour.Blue
Debug.Assert(test.HasColourChanged)

test.OriginalColour = MyColour.Blue
test.NewColour = MyColour.Blue
Debug.Assert(Not(test.HasColourChanged))

test.OriginalColour = Nothing
test.NewColour = MyColour.Blue
Debug.Assert(test.HasColourChanged)

test.OriginalColour = MyColour.Blue
test.NewColour = Nothing
Debug.Assert(test.HasColourChanged)

test.OriginalColour = Nothing
test.NewColour = Nothing
Debug.Assert(Not(test.HasColourChanged))

您可以使用Nullable.Equals方法。让事情变得美好和简单。

Public ReadOnly Property HasColourChanged As Boolean
    Get
        Return Not Nullable.Equals(OriginalColour, NewColour)
    End Get
End Property