简体   繁体   English

使用来自另一个子的参数调用子

[英]Call a Sub With Parameters from Another Sub

Good day Gurus.老师们好。 Am trying to call a Sub that has parameter from another Sub using Action but not working.我正在尝试使用 Action 调用具有来自另一个 Sub 的参数但不工作的 Sub。 Please I have tried to solve this error but couldn't.请我尝试解决此错误,但无法解决。

I have two Sub in my BasePage in ASP.Net as shown below;我在 ASP.Net 的 BasePage 中有两个Sub ,如下所示;

Sub Check(mySub As Action)
    mySub()
End Sub
Sub TestMsg(g As String)
    MsgBox(g)
End Sub

And on click event LinkButton, am trying to call TestMsg through Check as below在点击事件 LinkButton 上,我试图通过Check调用TestMsg ,如下所示

Private Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
    Check(AddressOf TestMsg("Call a sub from another"))
End Sub

But am getting an error message that says addressof operand must be the name of a method (without parenthesis)但是我收到一条错误消息,指出操作数的地址必须是方法的名称(不带括号)

Please what is the solution to this?请问这个有什么解决办法?

Thanks in advance提前致谢

You can get around it with a trick, but it feels like it defeats the purpose你可以用诡计绕过它,但感觉它违背了目的

Private Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
    Check(Sub() TestMsg("Call a sub from another"))
End Sub

To make it work the way you want, you might make a generic overload and call that为了让它按照你想要的方式工作,你可以做一个通用的重载并调用它

Sub Check(mySub As Action)
    mySub()
End Sub
Sub Check(Of T)(mySub As Action(Of T), arg As T)
    mySub(arg)
End Sub
Sub TestMsg(g As String)
    MsgBox(g)
End Sub

Private Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
    Check(AddressOf TestMsg, "Call a sub from another")
End Sub

Still, it would be easier to just call不过,打电话会更容易

TestMsg("Call a sub from another")

vb.net does have "CallByName" feature. vb.net 确实具有“CallByName”功能。

You can specify the sub you call by passing a string name.您可以通过传递字符串名称来指定您调用的子程序。

So, say this code:所以,说这段代码:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

   Dim strSubToCall As String

    strSubToCall = "Sub1"
    CallByName(Me, strSubToCall, CallType.Method)

    strSubToCall = "Sub2"
    CallByName(Me, strSubToCall, CallType.Method, "String value passed")

    strSubToCall = "Sub3"
    CallByName(Me, strSubToCall, CallType.Method, "String value passed", 55)



End Sub

Sub Sub1()

    Debug.Print("Sub 1 called")

End Sub

Sub Sub2(s As String)

    Debug.Print("Sub 2 called - value passed = " & s)

End Sub

Sub Sub3(s As String, i As Integer)

    Debug.Print("Sub 3 called, values passed = " & s & " - " & i.ToString)

End Sub

output: output:

Sub 1 called
Sub 2 called - value passed = String value passed
Sub 3 called, values passed = String value passed - 55

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM