开发者

Translating delegate usage from C# to VB

In physics library written in C# I have the following code:

(in ContactManager.cs)

public delegate void PostSolveDelegate(Contact contact, ref ContactImpulse impulse);
public PostSolveDelegate PostSolve;

And an example that uses that code is:

(in Test.cs)

public virtual void PostSolve(Contact contact, ref ContactImpulse impulse)
{
}

ContactManager.PostSolve += PostSolve;

I'd like to do the same in VB. (just thandling the delegate, not the declaration)

I tried this, but it doesn't work:

AddHandler ContactManager.PostSolve, AddressOf PostSolve

The following works, but only allows me t开发者_开发百科o have one handler for the delegate:

ContactManager.PostSolve = new PostSolveDelegate(AddressOf PostSolve)

Is there a way for me to do the same thing in VB that was done in the first piece of code?

Thanks!


A delegate can be a multicast delegate. In C# you can use += to combine multiple delegates into a single multicast delegate. Usually you see this done as an event and then use AddHandler in VB to add multiple delegates to the event.

But if you did something like this:

Public Delegate Sub PostSolver()

and then declared the field in a class:

Private PostSolve As PostSolver

and then created two delegates and used Delegate.Combine to combine them:

Dim call1 As PostSolver
Dim call2 As PostSolver
call1 = AddressOf PostSolve2
call2 = AddressOf PostSolve3

PostSolve = PostSolver.Combine(call1, call2)

You can call PostSolve() and both delegates will be called.

Might be easier just to make it an Event which is setup to do this without the extra hassle.

Update: To remove a delegate from the list you use the Delegate.Remove method. But you must be careful to use the return value as the new multicast delegate or it will still call the delegate you thought you removed.

PostSolve = PostSolver.Remove(PostSolve, call1)

Calling PostSolve will not call the first delegate.


Do you declare the PostSolve as an event in the ContactManager class? You need to declare it as follows:

Public Event PostSolve()

You can't do this AddHandler ContactManager.PostSolve, AddressOf PostSolve because the PostSolve is not an event here, but a delegate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜