GoTo、使用 Select 和使用单独的函数有什么区别?

What's the difference between GoTo, using a Select, and using separate function?

首先,我知道使用 Goto 从来都不是一个好主意。但是我很难看出以下结构之间的区别......它们都是顺序处理条件,当找到真值时停止处理,然后 return 控制到代码中的指定位置(下一行,因为那是这个特定 'GoTo' 目标所在的位置)。有什么区别:

Ifs with GoTo:

If ConditionA then 'This is designed to skip the evaluation of condition B if condition A is met.
    Do something
    Goto Resume
End If
If ConditionB then
    Do something
    Goto Resume
End If
Resume:

Select 案例:

Select ConditionIsTrue 'This will also skip the evaluation of B if A is true.
    Case A
        Do something
    Case B
        Do something
End select

单独子:

EvaluateConditions(condition)

Sub EvaluateConditions(condition)
    If A then
        DoSomething
        Exit Sub
    End If
    If B then
        DoSomething
        Exit Sub
     End If
End Sub

一般来说,

  1. 'goto' 将执行控制转移到您正在分配的标签。控件永远不会返回到您使用 'goto' 的位置。由于程序流程完全改变,不建议使用'goto'。调试变得困难。

  2. 当您编写子例程并从代码的其他部分调用它时,一旦子例程执行完成,控制权就会转移回代码的被调用部分。因此,与 goto 不同,程序流程不会受到影响,并且始终建议使用子例程而不是 goto。

  3. 在select语句的情况下,它与多个'if-else'语句没有太大区别。您可以使用 'select' 来获得更简洁的代码,而不是使用太多 'if-else'。

具体到你问的,三个都是一样的,没有区别。您选择什么取决于您的要求、条件数量、代码段的可重用性和未来的增强功能。

如果您的条件很少(2 或 3)并且您确定这段代码不需要将来的增强,那么 'ok' 使用 goto。(仍然不是很好选择)

如果这段代码应该是可重用的,甚至是其他的,使用子程序是最好的选择。事实上,即使你有很少的条件,最好在子程序中使用 'select' 语句,这样你的代码看起来很干净,并且将来很容易添加更多条件。