2013-08-02 32 views
0

嘗試將方法添加到委託時,我不斷收到錯誤「方法名稱預期」。我有一個委託,當我的比賽結束時被調用。我試圖添加到委託函數停止從閃爍倒計時(該方法是在一個靜態類)。我搜索了一下,我仍然不確定它爲什麼不工作。下面是導致錯誤的行:嘗試向委託添加處理程序方法時出現「方法名稱預期」錯誤 - C#

LivesManager.gameEnded += new LivesManager.EndGame(CountdownManager.DisableFlashTimer(this));

this傳遞電流的形式向方法,因此可以禁用窗體上的計時器閃光燈。

我已經將方法從靜態類添加到同一個委託之前,它工作正常,唯一的區別是,我通過表單作爲參數,然後它不喜歡它。

有沒有任何方法可以將表單傳遞給沒有錯誤的方法?

感謝提前:)

回答

0

我假設一點點,因爲你還沒有包括的gameEndedEndGame的定義。我相信問題是CountdownManager.DisableFlashTimer(this)不是方法名稱,但實際上是一個方法調用。編譯器試圖將此方法調用的最終返回值傳遞給構造函數LivesManager.EndGame,而LivesManager.EndGame很可能是(void parameterless?)Delegate。

也許你打算:

LivesManager.gameEnded += 
    new LivesManager.EndGame(() => CountdownManager.DisableFlashTimer(this)); 

或者乾脆:

LivesManager.gameEnded +=() => CountdownManager.DisableFlashTimer(this); 
+0

此作品謝謝:)不過我有點困惑的lambda表達式:從我的lambda表達式的參數的知識該方法將在'()'中,就像'new LivesManager.EndGame((this)=> CountdownManager.DisableFlashTimer);'你能解釋一下嗎? – darkstar

+0

由lambda創建的匿名函數的參數名在括號內。所以'(this)=> ...'會嘗試使用一個名爲「this」的參數來創建一個函數,類似於使用'ReturnType MyFunc1(int this)'的方法(因爲它是保留字會被禁用)。 '()=> ...'的lambda表達式類似於'ReturnType MyFunc()'方法,其中'ReturnType'在這種情況下是'void',因爲沒有任何東西被返回。所以'()=> CountdownManager.DisableFlashTimer(this)'類似於'void MyFunc(){CountdownManager.DisableFlashTimer(this); }' –

+0

好吧,我想我得到它:)只是一個更多的問題:如何來新''LivesManager.EndGame(()=> CountdownManager.DisableFlashTimer(this));'工作方式與'()=> CountdownManager.DisableFlashTimer這一點);'?我一直在學習最近提及[link](http://www.codeproject.com/Articles/13607/A-Beginner-s-Guide-to-Delegates)的代表。在該教程中,委託給出了一個處理器方法,如'LivesManager.gameEnded + = new LivesManager.EndGame((=)=> CountdownManager.DisableFlashTimer(this));'。使用更簡單的版本會有什麼損失嗎? – darkstar

0

您可以使用lambda表達式:

LivesManager.gameEnded +=() => CountdownManager.DisableFlashTimer(this);