2009-08-08 36 views
0

功能我有這個片段回到在C#

private void westButton_click(object sender, EventArgs ea) 
{ 
    PlayerCharacter.Go(Direction.West); 
} 

重複北部,南部和東部。

我該如何聲明一個讓我可以通過編程方式生成方法的函數?

例如,我希望能夠調用

northButton.Click += GoMethod(Direction.North); 

而不是定義的方法,然後

northButton.Click += new EventHandler(northButton.Click); 
+0

也許返回一個代表? – eKek0 2009-08-08 03:55:41

回答

4
northButton.Click += (s, e) => GoMethod(Direction.North); 

(或......)

northButton.Click += (s, e) => PlayerCharacter.Go(Direction.North); 
0
northButton.Click += (s,e) => GoMethod(Direction.North); 
+0

()=> PlayerCharacter.Go(Direction.North) – 2009-08-08 04:08:55

+2

如何將不帶參數的lambda表達式添加到事件中作爲需要兩個參數的委託的處理程序:object和EventArgs?它應該是(s,e)=> PlayerCharacter.Go(Direction.North)或者委託{PlayerCharacter.Go(Direction.North);} – 2009-08-08 04:23:46

0

我似乎已經找到了解決辦法:

private EventHandler GoMethod(Direction dir) 
{ 
    return new EventHandler((object sender, EventArgs ea) => PlayerCharacter.Go(dir)); 
} 

我唯一關心的是關於綁定ti我;如果PlayerCharacter是null,當我調用GoMethod時,會發生什麼?

+1

PlayerCharacter和dir變量被閉包捕獲(關閉)。編譯器會在幕後生成額外的代碼,將它們「提升」到它們自己的私有類和實例中,以便在代碼運行時保持它們的狀態。 – 2009-08-08 04:14:59