0
我有一個基類,它實現接口IEquatable使用它:實施IEquatable在基類和所有派生類
Public MustInherit Class DaoBase : Implements IEquatable(Of DaoBase)
MustOverride Function getPrimaryKey() As Integer
Shadows Function Equals(other As DaoBase) As Boolean Implements IEquatable(Of DaoBase).Equals
Return getPrimaryKey() = other.getPrimaryKey
End Function
Overrides Function GetHashCode() As Integer
Return getPrimaryKey()
End Function
' more things here
End Class
所有子類必須提供一個getPrimaryKey
方法。
Public Class Packaging
Inherits DaoBase
Public Sub New(id As Integer)
Me.id = id
End Sub
Overrides Function getPrimaryKey() As Integer
Return id
End Function
<DaoField> Property id As Integer
End Class
List(Of Packaging).Contains
永遠不會調用按預期的方式Equals
方法。
Dim packs As new List(Of Packaging)()
Dim pack As New Pack(1)
Dim pack2 As New Pack(1)
packs.Add(pack)
現在,packs.Contains(pack)
< - TRUE,OK,參考平等
但是,packs.Contains(pack2)
< - FALSE,NOK!
我不想「記住」在派生類中實現IEquatable
。
有沒有辦法強制派生來實現他們的IEquatable
,或者,甚至更好的做法是讓Contains
調用基類DaoBase.Equals
?
你在這行'getPrimaryKey()= other.getPrimaryKey'的末尾是否缺少'()'? – dasblinkenlight 2015-03-31 18:48:54
您的代碼應該正常工作 - 這是[* Template Method *](http://en.wikipedia.org/wiki/Template_method_pattern)設計模式的經典實現。 – dasblinkenlight 2015-03-31 18:50:39
IEquatable是爲結構否? –
2015-03-31 18:51:24