比较Nullable Enum(vb)

时间:2015-01-07 05:05:52

标签: vb.net enums nullable equality

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

我有2个可以为空的Enum&#39。我想将它们相互比较,其中一个或两个可以为null。我必须单独测试相等性并测试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

3 个答案:

答案 0 :(得分:2)

您可以使用Nullable.Equals方法。让事情变得简单明了。

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

答案 1 :(得分:0)

您只对一个条件返回false,因此使您的属性作为默认值返回true并且仅在满足条件时返回false,这样您就不必检查返回true。因此,你不会需要这么多条件,以下就足够了

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

答案 2 :(得分:0)

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

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))