在基类中实现IEquatable并在所有派生类中使用它

时间:2015-03-31 18:45:15

标签: .net vb.net interface containers

我有一个实现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)&lt; - TRUE,OK,引用相等

但是,packs.Contains(pack2)&lt; - FALSE,NOK!

我不想&#34;记得&#34;在派生类中实现IEquatable

有没有办法强制派生来实现他们的IEquatable,或者甚至更好地让Contains调用基类DaoBase.Equals

1 个答案:

答案 0 :(得分:0)

我发现的唯一解决方案是对基类进行泛化:

Public MustInherit Class DaoBase(Of T) : Implements IEquatable(Of T)

    MustOverride Shadows Function Equals(other As T) As Boolean Implements IEquatable(Of T).Equals
    MustOverride Overrides Function GetHashCode() As Integer

End Class

Public Class Packaging
    Inherits DaoBase(Of Packaging)

    Public Sub New(id As Integer)
        Me.id = id
    End Sub

    Overrides Function Equals(other As Packaging) As Boolean
        Return GetHashCode() = other.GetHashCode()
    End Function

    Overrides Function GetHashCode() As Integer
        Return id
    End Function

    Property id As Integer
End Class

现在必须覆盖Equals并将其专门用于派生类型。

    Dim p1 As New Packaging(1)
    Dim p2 As New Packaging(1)

    Dim packs As New List(Of Packaging)
    packs.Add(c1)

    Debug.Print(packs.Contains(c1))         <- TRUE
    Debug.Print(packs.Contains(c2))         <- TRUE

但是我必须在所有派生类中编写许多相同的Equals方法。我一直在寻找避免这种情况的方法。