我需要比较Web应用程序中VB.NET中两个对象列表的值。我似乎找不到任何可行的方法来实现此目的。
他们在那里实现了自定义界面。但是即使使用精确的代码也会给我带来错误。
这是我当前正在尝试的代码。与Microsoft的示例基本相同,但使用我自己的类:
Public Class ForumWithName
Inherits IEquatable(Of ForumWithName)
Private mForumID As Integer
Public Property ForumID() As Integer
Get
Return mForumID
End Get
Set(value As Integer)
mForumID = value
End Set
End Property
Private mForumName As String
Public Property ForumName As String
Get
Return mForumName
End Get
Set(value As String)
mForumName = value
End Set
End Property
Private mSubscribed As Boolean
Public Property Subscribed As Boolean
Get
Return mSubscribed
End Get
Set(value As Boolean)
mSubscribed = value
End Set
End Property
Public Function Compare(ByVal other As ForumWithName) As Boolean
If other Is Nothing Then Return False
Return Me.ForumID = other.ForumID AndAlso Me.Subscribed = other.Subscribed
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Return Compare(TryCast(obj, ForumWithName))
End Function
Public Overrides Function GetHashCode() As Integer
Return (ForumID, Subscribed).GetHashCode()
End Function
End Class
由于一些错误,此代码无法编译: “类只能从其他类继承” “未定义或导入预定义类型'ValueTuple(Of,)。 “ Visual Basic 10.0不支持元组” “'GetHashCode'不是'((ForumID为整数,已订阅为Boolean)'的成员”'
一旦我使此代码正常工作,我的计划就是比较上面两个“ ForumWithName”类的列表。
例如(假设SubscribedForum1和SubscribedForums2都是List(属于ForumWithName)):
If SubscribedForums1.SequenceEqual(SubscribedForums2) Then
Return True
Else
Return False
End If
答案 0 :(得分:2)
IEquatable
是一个接口,需要实现而不是继承。 (我猜这里,但是我认为这是您链接的MSDN页面中的错字)
更改以下类的声明:
Public Class ForumWithName
Inherits IEquatable(Of ForumWithName)
成为
Public Class ForumWithName
Implements IEquatable(Of ForumWithName)
完成此操作后,还需要添加此功能
Public Overloads Function Equals(other As ForumWithName) As Boolean Implements IEquatable(Of ForumWithName).Equals
Return Compare(TryCast(other, ForumWithName))
End Function
要解决无法使用元组的问题,您应该可以使用以下方法:
Public Overrides Function GetHashCode() As Integer
Return (ForumID & Subscribed).GetHashCode()
End Function
编辑:
顺便说一句,您可能想在ForumName
函数中包含属性Subscribed
和GetHashCode
,以检查对象之间是否真正相等。