System.Collections.Generic集合和IEquatable错误

时间:2016-12-07 15:09:18

标签: .net vb.net generics interface iequatable

我有以下类基于Microsoft MSDN的示例代码:

Imports System.Collections.Generic
Module SharedCode

    Public Class Fund
        Implements IEquatable(Of Fund)

    'Class Fund must implement Function Equals(other As RetirementCalcOverTime.SharedCode.Fund) As Boolean for interface System.IEquatable(Of Fund)

        Public Property FundName As String
        Public Property StartDate As Date
        Public Property StartBalance As Double
        Public Property StartQuantity As Double
        Public Property StartPrice As String

        Public Sub New()
        End Sub
        Public Sub New(ByVal sFundName As String,
                                     ByVal dStartDate As Date,
                                     ByVal pStartBalance As Double,
                                     ByVal pStartQuantity As Double,
                                     ByVal pStartPrice As Double)
            FundName = sFundName
            StartDate = dStartDate
            StartBalance = pStartBalance
            StartQuantity = pStartQuantity
            StartPrice = pStartPrice
        End Sub
        Public Function Overrides Equals(ByVal obj As Fund) As Boolean 

        'Overrides is flagged as invalid identifier

            If obj Is Nothing Then
                Return False
            End If
            Dim objAsFund As Fund = TryCast(obj, Fund)
            If objAsFund Is Nothing Then
                Return False
            Else
                Return Equals(objAsFund)
            End If
        End Function

    End Class

End Module

我做错了什么覆盖和Equals函数抛出错误?

2 个答案:

答案 0 :(得分:0)

您需要两个功能:

Public Function Overrides Equals(ByVal obj As Object) As Boolean

覆盖Object.Equals

Public Function Equals(ByVal obj As Fund) As Boolean Implements IEquatable(Of Fund).Equals

实现接口方法。

您当前的实现适用于第一种方法(因为您检查是否Fund),前提是您将参数类型更改为Object - 现在您只需要第二种方法为两个Fund对象定义“相等”,这将满足接口实现。

您还应该覆盖GetHashCode以与您的相等定义保持一致(两个“相等”对象必须返回相同的哈希码)。

答案 1 :(得分:0)

问题在于等于:

 Public Overrides Function Equals(obj As Fund) As Boolean
     If obj Is Nothing Then
         Return False
     End If
     Dim objAsFund As Fund = TryCast(obj, Fund)
     If objAsFund Is Nothing Then
         Return False
     Else
        If Me.FundName == objAsFund.FundName AndAlso ...
     End If
 End Function

你应该把你的条件(例如所有属性都相同)而不是'...'