2016-12-07 85 views
0

我有一個基於示例代碼從MSDN微軟以下類:System.Collections.Generic收集和IEquatable錯誤

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函數拋出錯誤?

+1

VS/VB將增加你需要的時候你在'Implements ...'行上按回車鍵 – Plutonix

+0

這擺脫了執行錯誤,所以感謝那個Plutonix。 – twellsles

回答

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以與您的相等定義一致(兩個「相等」對象必須返回相同的散列碼)。

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 

你應該把你的條件(例如所有屬性都一樣),而不是「...」

+0

擊中行後回車鍵:實現IEquatable(基金) 增加了以下內容: \t \t公共功能Equals1(其他如基金)爲布爾器具IEquatable(基金).Equals \t \t端功能 我必須有點慢,因爲我不知道該怎麼做,因爲MSDN沒有提到它,並說覆蓋Equals。我在這裏錯過了什麼? – twellsles