我正在将DataTables转换为通用列表,并且需要一种快速简便的方法来实现Find函数。看来我将不得不使用Predicate。经过进一步调查,我似乎仍然无法重新创建功能。我有这个谓词......
Private Function ByKey(ByVal Instance As MyClass) As Boolean
Return Instance.Key = "I NEED THIS COMPARISON TO BE DYNAMIC!"
End Function
然后这样称呼它......
Dim Blah As MyClass = MyList.Find(AddressOf ByKey)
但我没有办法将一个关键变量传递给这个谓词进行比较,就像我以前用DataTable做的那样......
Dim MyRow as DataRow = MyTable.Rows.Find(KeyVariable)
如何在VB.NET中设置谓词委托功能来实现这一目标?
不建议使用LINQ或lambdas,因为这是关于.NET 2.0版的问题。
答案 0 :(得分:5)
只需将谓词放在类实例中:
Public Class KeyMatcher
Public Sub New(ByVal KeyToMatch As String)
Me.KeyToMatch = KeyToMatch
End Sub
Private KeyToMatch As String
Public Function Predicate(ByVal Instance As MyClass) As Boolean
Return Instance.Key = KeyToMatch
End Function
End Class
然后:
Dim Blah As MyClass = MyList.Find(AddressOf New KeyMatcher("testKey").Predicate)
我们甚至可以有点想象,并使这个通用:
Public Interface IKeyed(Of KeyType)
Public Key As KeyType
End Interface
Public Class KeyMatcher(Of KeyType)
Public Sub New(ByVal KeyToMatch As KeyType)
Me.KeyToMatch = KeyToMatch
End Sub
Private KeyToMatch As KeyType
Public Function Predicate(ByVal Instance As IKeyed(Of KeyType)) As Boolean
Return Instance.Key = KeyToMatch
End Function
End Class
然后让你的MyClass类型实现新的IKeyed接口