2

我一直在我的代码上运行 FxCop,它报告了许多 CA2224 和 CA1815 错误,因为结构拥有Operator =功能但没有覆盖.Equals. 作为一个尽职尽责的人,我正在努力纠正这些,但遇到了问题。我因此创建了一个结构:-

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

我尝试.Equals像这样覆盖运算符:-

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

这会产生编译错误function 'Equals' cannot be declared 'Overrides' because it does not override a function in a base structure

但是当我尝试时: -

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

这会产生警告function 'Equals' shadows an overridable method in the base class 'ValueType'. To override the base method, this method must be declared 'Overrides'

换句话说,我必须并且可能不会将方法声明为overrides. 谁能帮我解决这个问题?

4

1 回答 1

4

您必须将函数参数指定为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

但是,我不确定它是否会改变标准Structure比较行为 - 默认情况下比较结构中的每个值。

于 2013-02-26T15:51:30.530 回答