2010-04-01 42 views
1

在物理库C#编写的我有以下代码:翻译代表使用到VB

(在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。 (只是thandling委托,而不是声明)

我尝试这样做,但它不工作:

AddHandler ContactManager.PostSolve, AddressOf PostSolve 

以下的作品,但只允许我有一个处理程序委托:

ContactManager.PostSolve = new PostSolveDelegate(AddressOf PostSolve) 

有没有一种方法可以让我在第一部分代码中完成同样的事情?

谢谢!

+0

标题有点混乱:这是从C#到VB,而不是相反,对不对? – 2010-04-01 02:17:32

+0

您能向我们展示“PostSolve”声明吗? – 2010-04-01 02:36:50

+0

编辑显示声明,并为我编辑标题:)谢谢! – 2010-04-01 11:00:35

回答

3

委托可以是多播委托。在C#中,您可以使用+ =将多个委托合并为一个多播委托。通常你将这看作是一个事件,然后在VB中使用AddHandler将多个委托添加到事件中。

但是,如果你做了这样的事情:

Public Delegate Sub PostSolver() 

,然后宣布在一类领域:

Private PostSolve As PostSolver 

,然后创建了两个代表和使用Delegate.Combine把它们结合起来:

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

PostSolve = PostSolver.Combine(call1, call2) 

你可以调用PostSolve()并且两个委托都会被调用。

可能会更容易,只是为了让它成为一个事件而设置,无需额外的麻烦。

更新:若要从列表中删除委托,请使用Delegate.Remove方法。但是,您必须小心使用返回值作为新的多播委托,否则它仍将调用您认为已删除的委托。

PostSolve = PostSolver.Remove(PostSolve, call1) 

调用PostSolve不会调用第一个委托。

+0

当你在C#中的委托中调用+ =时会发生什么?如果是这样,我会调用Delegate.Remove(ContactManager.PostSolver,PostSolver)将其从委托中删除吗? – 2010-04-01 10:58:39

+0

是的。我用一个例子更新了答案。 – 2010-04-01 13:52:05

1

您是否将PostSolve声明为ContactManager类中的事件? 您需要如下声明它:

Public Event PostSolve() 

你不能做到这一点AddHandler ContactManager.PostSolve, AddressOf PostSolve 因为PostSolve不在这里一个事件,而是一个委托。

+0

我编辑了我的帖子以显示声明。不幸的是,我不能改变它,因为它是一个单独的库。 – 2010-04-01 11:00:04

+0

然后,我认为你应该做爸爸的解决方案。 – 2010-04-03 06:50:49