使用带有自定义谓词的 List.Find 时遇到一些问题
我有一个函数可以做到这一点
private function test ()
Dim test As Integer = keys.Find(AddressOf FindByOldKeyAndName).NewKey
这是谓词的函数
Private Shared Function FindByOldKeyAndName(ByVal k As KeyObj) As Boolean
If k.OldKey = currentKey.OldKey And k.KeyName = currentKey.KeyName Then
Return True
Else
Return False
End If
End Function
通过这样做意味着我必须在类中拥有一个共享的“currentKey”对象,并且我知道必须有一种方法来传递我感兴趣的 CurrentKey 值(即键名和旧键)
理想情况下我想用类似的方式来称呼它keys.Find(AddressOf FindByOldKeyAndName(Name,OldVal))
但是,当我这样做时,我收到编译器错误。
我如何调用这个方法并传入值?
您可以使用 VS2008 及更高版本中提供的 lambda 表达式干净地解决此问题。一个愚蠢的例子:
Sub Main()
Dim lst As New List(Of Integer)
lst.Add(1)
lst.Add(2)
Dim toFind = 2
Dim found = lst.Find(Function(value As Integer) value = toFind)
Console.WriteLine(found)
Console.ReadLine()
End Sub
对于早期版本,您必须将“currentKey”设置为类的私有字段。检查我的代码这个线程 http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/937ed805-99f2-4579-9356-d6676fc5dcb2以获得更清洁的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)