2010-04-01 21 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