同 GoTo。想「從函數中間開始執行」或「只執行一部分」,本質是控制流拆分與組合問題,應用現代模式解決。
' 原函數
Sub BigFunc()
PartA() ' 共用初始化
PartB() ' 核心邏輯1
PartC() ' 核心邏輯2
End Sub
' 需求:只執行 PartB + PartC
Sub EntryPoint1() { PartA(); PartB(); PartC(); }
Sub EntryPoint2() { PartB(); PartC(); } ' 直接調用所需部分
Sub FlexibleFunc(Optional skipInit As Boolean = False)
If Not skipInit Then Initialize()
CoreLogic()
Cleanup()
End Sub
' 調用
FlexibleFunc() ' 完整執行
FlexibleFunc(True) ' 跳過初始化
Delegate Sub Step()
Sub ExecuteSteps(ParamArray steps() As Step)
For Each s In steps: s.Invoke(): Next
End Sub
' 定義步驟
Sub Step1() : ... End Sub
Sub Step2() : ... End Sub
Sub Step3() : ... End Sub
' 只執行 2 和 3
ExecuteSteps(AddressOf Step2, AddressOf Step3)
Iterator Function Flow() As IEnumerable(Of Action)
Yield AddressOf Step1
Yield AddressOf Step2
Yield AddressOf Step3
End Function
' 使用:跳過第一步
For Each act In Flow().Skip(1)
act.Invoke()
Next
Class FlowEngine
Enum State { Start, AfterInit, Running, Done }
Private _state As State = State.Start
Public Sub Run(Optional startFrom As State = State.Start)
_state = startFrom
While _state <> State.Done
Select Case _state
Case State.Start: Init(); _state = State.AfterInit
Case State.AfterInit: Core(); _state = State.Running
Case State.Running: Finish(); _state = State.Done
End Select
End While
End Sub
End Class
' 從 AfterInit 開始
engine.Run(FlowEngine.State.AfterInit)
https://zhidao.baidu.com/question/1509889879601756100.html(結論一致:不支援跨函數 GoTo)。
核心思想:將「跳轉」轉化為「調用組合」。任何看似需要 GoTo 的場景,都是函數職責不夠單一、控制流不夠顯式的信號。