Alternative to GoSub in VB.net

2020-04-20 14:12发布

I'm assigned a project to replace all the GoSubs in an application based off of VBA because this application is switching to VB.net and GoSubs are not supported there. Here's a simplified version of the original code:

Sub Main ()
  Dim A As String
  ...
  If ConditionX Then A = "Black"
  Else A = "White"
  End If
  ...
  GoSub Execute
  ...
  Execute:
    Call BuiltInSub1 (A)
    Call BuiltInSub2 (A)
    'where BuiltInSubs are some predefined procedures within the application
    ...
  Return

End Sub

I'm thinking about using a Call to replace GoSub as follows:

Sub Main ()
  Dim A As String

  If ConditionX Then A = "Black"
  Else A = "White"
  End If
  ...
  Call Execute
  ...

End Sub

Sub Execute ()
   ...
   Call BuiltInSub1 (A)
   Call BuiltInSub2 (A)
   ...
End Sub

The obvious error of my modified version above is that variable A is not declared in Sub Execute. One option I can think of is redefining A in Sub Execute, but to do that, I will need to re-declare all variables used to define A in Main, where there are quite a few.

What would be the best/most efficient way to replace GoSub in my case?

2条回答
Deceive 欺骗
2楼-- · 2020-04-20 14:39

I believe that lamda functions may have nested variable scope) in VB.net

Dim A
Dim B
Dim xecute = function()
    BuiltInSub1(A)
    BuiltInSub2(A)
End Sub
A = 1
B=xecute()
A=2
B=xecute()
查看更多
贪生不怕死
3楼-- · 2020-04-20 14:54

Based on my comments above, your code should look like this:

Sub Main ()
  Dim A As String

  If ConditionX Then A = "Black"
  Else A = "White"
  End If
  ...
  Execute(A)
  ...

End Sub

Sub Execute(A As SomeType)
   ...
   BuiltInSub1(A)
   BuiltInSub2(A)
   ...
End Sub

If you do find that you need declare parameters ByRef, you might want to look at refactoring as a more long-term solution.

查看更多
登录 后发表回答