在用 C# 编写的物理库中,我有以下代码:
(在 ContactManager.cs 中)
public delegate void PostSolveDelegate(Contact contact, ref ContactImpulse impulse);
public PostSolveDelegate PostSolve;
使用该代码的示例是:
(在 Test.cs 中)
public virtual void PostSolve(Contact contact, ref ContactImpulse impulse)
{
}
ContactManager.PostSolve += PostSolve;
我想在 VB 中做同样的事情。 (只是处理委托(delegate),而不是声明)
我试过了,但是没用:
AddHandler ContactManager.PostSolve, AddressOf PostSolve
下面的工作,但只允许我有一个委托(delegate)的处理程序:
ContactManager.PostSolve = new PostSolveDelegate(AddressOf PostSolve)
有没有办法让我在 VB 中做与第一段代码相同的事情?
谢谢!
请您参考如下方法:
委托(delegate)可以是多播委托(delegate)。在 C# 中,您可以使用 += 将多个委托(delegate)组合成一个多播委托(delegate)。通常您会将此视为一个事件,然后使用 VB 中的 AddHandler 将多个委托(delegate)添加到该事件。
但是如果你做了这样的事情:
Public Delegate Sub PostSolver()
然后在类中声明字段:
Private PostSolve As PostSolver
然后创建两个委托(delegate)并使用 Delegate.Combine 将它们合并:
Dim call1 As PostSolver
Dim call2 As PostSolver
call1 = AddressOf PostSolve2
call2 = AddressOf PostSolve3
PostSolve = PostSolver.Combine(call1, call2)
您可以调用 PostSolve(),两个委托(delegate)都会被调用。
将其设置为可以轻松执行此操作的事件可能会更容易。
更新:要从列表中删除委托(delegate),您可以使用 Delegate.Remove 方法。但是您必须小心使用返回值作为新的多播委托(delegate),否则它仍会调用您认为已删除的委托(delegate)。
PostSolve = PostSolver.Remove(PostSolve, call1)
调用 PostSolve 不会调用第一个委托(delegate)。
