当 key 是一个对象时实现 containsKey

Implement containsKey when key is an object

我有这个class:

Public Class AdDimensionsToAdDetails
    Public Sub New()
    End Sub

    Public Overrides Function equals(adDimensions As AdDimensions) As Boolean
        If adDimensions Is Nothing Then
            Return False
        End If

        Return Me.adDimensionsToAdDetails.Keys.First().width = adDimensions.width AndAlso
            Me.adDimensionsToAdDetails.Keys.First().height = adDimensions.height

    End Function

    Public ReadOnly Property adDimensionsToAdDetails As Dictionary(Of AdDimensions, AdDetails)
        Get
            Return New Dictionary(Of AdDimensions, AdDetails) From {
                {New AdDimensions(300, 250), New AdDetails(New MinMaxJobsCount(3, 3), True)},
                {New AdDimensions(300, 50), New AdDetails(New MinMaxJobsCount(1, 1), False)},
                {New AdDimensions(728, 90), New AdDetails(New MinMaxJobsCount(3, 3), True)},
                {New AdDimensions(160, 600), New AdDetails(New MinMaxJobsCount(3, 7), True)}
            }

        End Get
    End Property

End Class

我想检查 adDimensionsToAdDetails 是否包含密钥 300,250。

所以我试过了:

dim adDimensions as new AdDimensions(300,250)

' it contains the key
if (AdDimensionsToAdDetails.adDimensionsToAdDetails.ContainsKey(adDimensions)) then

End If

我读到我需要覆盖 equals

所以我试过了,但我得到: function 'equals' cannot be declared 'overrides' because it does not override a function in a base class

感谢任何帮助!

您不能更改要覆盖的方法的签名。 Object.Equals 方法有一个 Object 类型的参数。您的覆盖必须相同。

话虽如此,我才发现您的方法有误class。如果目的是比较该类型的两个实例,则需要在 AdDimensions class 中。

Dictionary class 被实现为哈希表。比较键值时,Dictionary 将调用相关键项的 GetHashCode 方法,并且仅当它具有该特定哈希码的条目时,它才会调用该项的 Equals 方法验证相等性。

因此,要使用 Dictionary(Of AdDimensions, AdDetails).ContainsKey 方法,您需要重写 class AdDimensions 从 System.Object 继承的 EqualsGetHashCode 方法.

以下是一种可能的实现方式,基于您的代码。

Class AdDimensions
    Public Sub New(height As Int32, width As Int32)
        Me.height = height
        Me.width = width
    End Sub
    Public height As Int32
    Public width As Int32

    Public Overrides Function Equals(obj As Object) As Boolean
        Dim other As AdDimensions = TryCast(obj, AdDimensions)
        Dim ret As Boolean
        If other IsNot Nothing Then
            ret = (Me.width = other.width) AndAlso (Me.height = other.height)
        End If
        Return ret
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return Me.width Xor Me.height
    End Function
End Class