Jos*_*lds 4 .net vb.net lambda
我从以下一些精彩的遗留代码中摘录了以下内容:
Private Sub SomeMethod()
Dim deductibles As List(Of Integer) = GetDeductibles()
deductibles.RemoveAll(AddressOf LessThanMinDed)
EndSub
Private Function LessThanMinDed(ByVal i As Integer) As Boolean
Return i < MinimumDeductible()
End Function
Run Code Online (Sandbox Code Playgroud)
如果你是一个语言势利小人,我们可以这样写:
private void SomeMethod() {
List<int> deductibles = GetDeductibles();
deductibles.RemoveAll(LessThanMinDed);
}
private bool LessThanMinDed(int i) {
return i < MinimumDeductible();
}
Run Code Online (Sandbox Code Playgroud)
MinimumDeductible()进行数据库调用.有没有办法写这个没有写像x = MinimumDeductible() : RemoveAll(Function(i) i < x)(因为lambda不在这个版本的VB.NET),只会调用一次数据库?
像这样解决:
Public Class Foo
Private CachedMinimum As Integer
Private Sub SomeMethod()
Dim deductibles As List(Of Integer) = GetDeductibles()
Me.CachedMinimum = MinimumDeductible()
deductibles.RemoveAll(AddressOf LessThanMinDed)
End Sub
Private Function LessThanMinDed(ByVal i As Integer) As Boolean
Return i < CachedMinimum
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
答案真的取决于语言.在C#2中,我们没有lambda表达式,但我们确实有匿名方法...所以你可以写:
List<int> deductibles = GetDeductibles();
deductibles.RemoveAll(delegate(int i) { return i < MinimumDeductible(); });
Run Code Online (Sandbox Code Playgroud)
据我所知,VS 2005附带的VB版本没有相应的版本.