首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

VB.NET 子程序中用 GoTo 跳轉執行函數部分代碼:不可行,請用委託/迭代器/狀態機重構

     編輯:程式設計疑難解答

同 23899,VB.NET/C# 等結構化語言**不允許**跨方法/函數邊界使用 GoTo。想「從函數中間開始執行」或「只執行一部分」,本質是控制流拆分與組合問題,應用現代模式解決。

為什麼想用 GoTo 跳進函數?

  • 避免重複代碼(函數前半段共用)。
  • 根據條件跳過初始化/校驗。
  • 實現類似協程的「暫停/恢復」。

正確重構模式

1. 拆分粒度更細的函數(最簡單)

' 原函數
Sub BigFunc()
    PartA() ' 共用初始化
    PartB() ' 核心邏輯1
    PartC() ' 核心邏輯2
End Sub

' 需求:只執行 PartB + PartC
Sub EntryPoint1() { PartA(); PartB(); PartC(); }
Sub EntryPoint2() { PartB(); PartC(); } ' 直接調用所需部分

2. 參數控制執行路徑

Sub FlexibleFunc(Optional skipInit As Boolean = False)
    If Not skipInit Then Initialize()
    CoreLogic()
    Cleanup()
End Sub

' 調用
FlexibleFunc()          ' 完整執行
FlexibleFunc(True)      ' 跳過初始化

3. 委託/策略組合(動態決定步驟)

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)

4. 迭代器/生成器 (狀態機,C# yield / VB.NET Iterator)

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

5. 狀態機類(複雜流程)

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 的場景,都是函數職責不夠單一、控制流不夠顯式的信號。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved