【发布时间】:2015-05-05 17:32:51
【问题描述】:
我从一些精彩的遗留代码中摘录了以下内容:
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
如果你是语言势利小人,我们可以这样写:
private void SomeMethod() {
List<int> deductibles = GetDeductibles();
deductibles.RemoveAll(LessThanMinDed);
}
private bool LessThanMinDed(int i) {
return i < MinimumDeductible();
}
MinimumDeductible() 进行数据库调用。有没有办法编写这个而不写像x = MinimumDeductible() : RemoveAll(Function(i) i < x)(因为lambdas不在这个版本的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
【问题讨论】:
-
顺便说一句,我强烈建议您尝试迁移到更新版本的 VS。如果你真的必须从 VS2013 或 VS2015 开始,你仍然可以以 .NET 2.0 为目标......但你可以使用许多更新的语言功能。
-
@JonSkeet,我希望我能够做出这些决定……相信我,我会的。
-
每个 lambda 表达式都可以用一些 For 循环和条件编写,因此请使用可用的 .net 框架中的可用函数编写您自己的函数