VB.NET - 传递要在函数内使用的表达式

VB.NET - Passing expression to be used within a function

我的程序的一部分由一系列步骤组成,这些步骤要么完成,要么在一定时间间隔后超时。测试条件差异很大。如何编写单个函数来封装所有可能性?

要做到这一点,理想情况下我需要将必要的条件传递给函数函数中进行评估,而不是作为参数进行评估然后传递给函数。

这就是我理想中想要的(大大简化):

Private Function TestCondition(<CONDITION>) as Boolean 
  ' Returns True if <CONDITION> fulfilled within 10 seconds
  Dim sw as New Diagnostics.StopWatch
  sw.Start()
  While sw.ElapsedMilliseconds < 10000
    If <CONDITION> Return True
    System.Threading.Thread.Sleep(500)
  End While
  sw.Stop()
  Return False
End Function

函数应该与 returns 布尔值的任何表达式一起使用:

TestCondition(x=5)
TestCondition(System.IO.File.Exists("myfile")

显然,上述方法不起作用,因为指定条件的 结果 被传递给了函数,而不是条件本身。

根据其他阅读资料,我可能可以通过以下方式完成此任务:

但我还是不明白具体是怎么回事。

非常感谢您的帮助!

您可以将 lambda 传递给可以不断重新计算的函数。

Private Function TestCondition(predicate As Func(Of Boolean)) As Boolean
    Dim sw As New Diagnostics.Stopwatch()
    sw.Start()
    While sw.ElapsedMilliseconds < 10000
        If predicate() Then Return True
        System.Threading.Thread.Sleep(500)
    End While
    sw.Stop()
    Return False
End Function
Dim result = TestCondition(Function() File.Exists("myfile"))

基本和djv说的一样,

''' <summary>
''' waits for a condition for a number of seconds
''' </summary>
''' <param name="PredicateFunc">Function() conditional check )</param>
''' <param name="WaitForTMInSecs">seconds to wait</param>
''' <returns>boolean</returns>
''' <remarks></remarks>
Private Function TestCondition(PredicateFunc As Func(Of Boolean),
                                Optional WaitForTMInSecs As Integer = 10) As Boolean
    Dim sw As Diagnostics.Stopwatch = Diagnostics.Stopwatch.StartNew
    Dim _wait As TimeSpan = TimeSpan.FromSeconds(WaitForTMInSecs)
    Dim rv As Boolean = PredicateFunc()
    Do While Not rv AndAlso sw.Elapsed <= _wait
        System.Threading.Thread.Sleep(500)
        rv = PredicateFunc()
    Loop
    Return rv
End Function

测试,

    Dim result As Boolean
    result = TestCondition(Function() String.Equals("foo", "bar"), 2)
    result = TestCondition(Function() String.Equals("foo", "foo"), 2)
    result = TestCondition(Function() IO.File.Exists("myfile"), 2)