我正在做一些需要自定义比较器的LINQ,所以我创建了一个实现IEqualityComparer的新类。但是,当我使用它时,我每次都必须创建它的一个实例。
Dim oldListOnly = oldList.Except(newList, New MyEqualityComparer)
Dim newListOnly = newList.Except(oldList, New MyEqualityComparer)我可能误解了.NET是如何工作的,但是每次创建一个新的比较器似乎是浪费的。我真的只需要一个实例(相当于C++/C#中的静态)。
因此,我尝试创建一个“静态”类,它是in vb.net is a module。但是得到了一个'Implements' not valid in Modules错误。
然后,我尝试让Equals和GetHashCode函数在我的类上共享方法,但是得到了这个错误:Methods that implement interface members cannot be declared 'Shared'.
有什么办法来实现我的目标吗?或者我只是误解了幕后发生的事情?
发布于 2012-01-21 01:32:39
你的理解是正确的,尽管浪费不太可能被注意到。对于您的情况,您可以使用单例模式,通常如下所示:
Public Class MyEqualityComparer
Implements IEqualityComparer(Of whatever)
Private Sub New()
'no outsider creation
End Sub
Private Shared ReadOnly _instance As New MyEqualityComparer()
Public Shared ReadOnly Property Instance As MyEqualityComparer
Get
Return _instance
End Get
End Property
'other code
End Class发布于 2012-01-21 01:30:34
为什么不干脆这么做呢
Dim comparer = New MyEqualityComparer
Dim oldListOnly = oldList.Except(newList, comparer )
Dim newListOnly = newList.Except(oldList, comparer )https://stackoverflow.com/questions/8945375
复制相似问题