简体   繁体   中英

Can't override .Equals in Structure

I have been running FxCop over my code and it is reporting a number of CA2224 and CA1815 errors, due to structures possessing Operator = functions but no override for .Equals . Being a dutiful fellow I'm endeavouring to correct these but have run into a problem. I have created a structure thus:-

Public Structure MyStruct

    Public my_innards As Integer

    Public Shared Operator =(ByVal fs As MyStruct, ByVal ss As MyStruct) As Boolean
        Return fs.my_innards = ss.my_innards
    End Operator

    Public Shared Operator <>(ByVal fs As MyStruct, ByVal ss As MyStruct) As Boolean
        Return fs.my_innards <> ss.my_innards
    End Operator

End Structure

and I attempt to override the .Equals operator like so:-

Public Overrides Function Equals(ByVal ss As MyStruct) As Boolean
    Return Me.my_innards = ss.my_innards
End Function

This produces the compilation error function 'Equals' cannot be declared 'Overrides' because it does not override a function in a base structure

But when I try:-

Public Function Equals (ByVal ss As MyStruct) As Boolean
    Return Me.my_innards = ss.my_innards
End Function

this produces the warning function 'Equals' shadows an overridable method in the base class 'ValueType'. To override the base method, this method must be declared 'Overrides' function 'Equals' shadows an overridable method in the base class 'ValueType'. To override the base method, this method must be declared 'Overrides' .

In other words I must, and may not, declare the method as overrides . Can anyone help me out with this?

You have to specify function parameter as Object :

Public Structure MyStruct

    Public Property Test As Integer

    Public Overrides Function Equals(obj As Object) As Boolean
        If obj Is GetType(MyStruct) Then
            Return Test = CType(obj, MyStruct).Test
        End If
        Return False
    End Function

End Structure

However, I'm not sure it change anything with standard Structure comparison behavior - every value within the struct is compared by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM