我有这堂课:
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
任何帮助表示赞赏!
答案 0 :(得分:2)
Dictionary
类实现为哈希表。在比较键值时,Dictionary
将在有问题的关键项上调用GetHashCode
方法,并且只有当它具有该特定哈希码的条目时才会调用项目Equals
Dictionary(Of AdDimensions, AdDetails).ContainsKey
1}}验证相等的方法。
因此,要使用Equals
方法,您需要覆盖AdDimensions类继承自GetHashCode
的{{1}}和System.Object
方法。
以下是一种可能的实现,基于您的代码。
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
答案 1 :(得分:0)
您无法更改要覆盖的方法的签名。 Object.Equals
方法有一个Object
类型的参数。您的覆盖必须具有相同的内容。
那就是说,我刚刚意识到你在错误的班级里有这种方法。如果意图是比较该类型的两个实例,则需要在AdDimensions
类中。