男孩哦,男孩,这个头衔令人困惑!
最好用一个例子来解释..这就是我想要发生的事情。
{{1}}
所以我开始在alg1上运行我的代码。 alg1调用alg2,它记录了谁调用它(我正在考虑使用stackTrace.GetFrame(1).GetMethod()。Name)然后将其存储在局部变量中,然后alg2继续调用alg3。 alg3调用存储在局部变量m中的子。
现在我的情况有点复杂,因为alg1与alg2属于不同的类,但理论上我所要做的就是对在运行时定义的子进行跨类调用。有没有办法存储像这样的子?
答案 0 :(得分:2)
您的示例应该只需更改Action
和AddressOf
Dim m As Action
Public Sub alg1()
Call alg2()
End Sub
Public Sub alg2()
m = AddressOf alg1
Call alg3()
End Sub
Public Sub alg3()
Call m()
End Sub
另一种选择是将其作为参数传递:
Public Sub alg2()
alg3(AddressOf alg1)
End Sub
Public Sub alg3(m As action)
m()
End Sub
答案 1 :(得分:1)
这是一个运行上述想法的快速示例。
简化的控制台代码:
Public Module Module1
Private Delegate Sub CoolDelegate()
Private m As CoolDelegate
Public Sub Main()
Debug.WriteLine("Calling Alg1")
Alg1()
End Sub
Private Sub Alg1()
Debug.WriteLine("Alg1 Called")
Debug.WriteLine("Calling Alg2")
Alg2()
End Sub
Private Sub Alg2()
Debug.WriteLine("Alg2 Called")
m = New CoolDelegate(AddressOf Alg1)
Debug.WriteLine("Calling Alg3")
Alg3()
End Sub
Private Sub Alg3()
Debug.WriteLine("Alg3 Called")
Debug.WriteLine("Calling m")
m()
End Sub
End Module
输出:
Calling Alg1
Alg1 Called
Calling Alg2
Alg2 Called
Calling Alg3
Alg3 Called
Calling m
Alg1 Called
Calling Alg2
Alg2 Called
Calling Alg3
Alg3 Called
Calling m
Alg1 Called
Calling Alg2
Alg2 Called
Calling Alg3
Alg3 Called
Calling m
Alg1 Called
Calling Alg2
(...重复直到堆栈溢出...)
它也可以被修改以摆脱本地私有变量。这是另一个版本......
Public Module Module1
Private Delegate Sub CoolDelegate()
Public Sub Main()
Debug.WriteLine("Calling Alg1")
Alg1()
End Sub
Private Sub Alg1()
Debug.WriteLine("Alg1 Called")
Debug.WriteLine("Calling Alg2")
Alg2(AddressOf Alg1)
End Sub
Private Sub Alg2(Caller As CoolDelegate)
Debug.WriteLine("Alg2 Called")
Debug.WriteLine("Calling Alg3")
Alg3(Caller)
End Sub
Private Sub Alg3(Caller As CoolDelegate)
Debug.WriteLine("Alg3 Called")
Debug.WriteLine("Calling Caller")
Caller()
End Sub
End Module