Alternative to GoSub in VB.net

杀马特。学长 韩版系。学妹 提交于 2019-12-02 08:54:33

问题


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?


回答1:


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.




回答2:


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()


来源:https://stackoverflow.com/questions/53330753/alternative-to-gosub-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!