gpt4 book ai didi

.net - IEquatable(Of T)/IEqualityComparer(Of T)不被调用

转载 作者:行者123 更新时间:2023-12-04 05:24:22 26 4
gpt4 key购买 nike

我有一些带有两个对象列表的代码。第一个列表比第二个列表更具包容性。我希望从第一个列表中排除第二个列表中的项目。经过一番研究,我发现扩展方法 Except是这样做的方法。我为此实现了 IEquatable(Of T)IEqualityComparer(Of T)在我的代码中是这样的:

Partial Public Class CustomerData
Implements IEquatable(Of CustomerData)
Implements IEqualityComparer(Of CustomerData)

Public Overloads Function Equals(other As CustomerData) As Boolean Implements IEquatable(Of ToolData.CustomerData).Equals
If other Is Nothing Then
Return False
Else
Return Me.CustomerID = other.CustomerID
End If
End Function

Public Overloads Function Equals(this As CustomerData, that As CustomerData) As Boolean Implements IEqualityComparer(Of ToolData.CustomerData).Equals
If this Is Nothing OrElse that Is Nothing Then
Return False
Else
Return this.CustomerID = that.CustomerID
End If
End Function

Public Overloads Function GetHashCode(other As CustomerData) As Integer Implements IEqualityComparer(Of ToolData.CustomerData).GetHashCode
If other Is Nothing Then
Return CType(0, Integer).GetHashCode
Else
Return other.CustomerID.GetHashCode
End If
End Function

然后我像这样打一个简单的电话:

customerCollection = CustomerData.LocalCustomers.Except(CustomerData.RecentCustomers).OrderBy(Function(x) x.FullName).ToList

这不起作用。这也不行:

customerCollection = CustomerData.LocalCustomers.Except(CustomerData.RecentCustomers, EqualityComparer(Of CustomerData).Default).OrderBy(Function(x) x.FullName).ToList

但是,这确实有效:

customerCollection = CustomerData.LocalCustomers.Except(CustomerData.RecentCustomers, New CustomerData).OrderBy(Function(x) x.FullName).ToList

RecentCustomersLocalCustomers都是 List(Of CustomerData)为什么默认的比较方法不起作用?当我说它不起作用时,我的意思是我可以在 Equals 中放置断点和 GetHashCode例程,它们永远不会被命中,返回的列表与 LocalCustomers 的列表相同。 .

最佳答案

首先,您不需要实现 IEqualityComparer(Of T)界面;如果您想为同一个类提供多种类型的相等性,您通常会在另一个类中实现它。

其次,您需要覆盖 GetHashCodeEquals(Object)方法:

Partial Public Class CustomerData
Implements IEquatable(Of CustomerData)

Public Override Function GetHashCode() As Integer
Return CustomerID.GetHashCode()
End Function

Public Override Function Equals(ByVal obj As Object)
Return Equals(TryCast(obj, CustomerData))
End Function

Public Overloads Function Equals(other As CustomerData) As Boolean Implements IEquatable(Of ToolData.CustomerData).Equals
If other Is Nothing Then
Return False
Else
Return Me.CustomerID = other.CustomerID
End If
End Function

...

这是一篇博客文章,解释了原因:
http://blogs.msdn.com/b/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.aspx

关于.net - IEquatable(Of T)/IEqualityComparer(Of T)不被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com