2011-04-13 74 views
0

時具有誤差我有以下:我創建事件

遊戲類

class Game 
{ 
    public event EventHandler GameOver; 

    public void go() 
    { 
     PlayerAliveEventArgs playerAlive = new PlayerAliveEventArgs(Alive); 
     GameOver(this, playerAlive); 
    } 
} 

然後我在另一個類的類

public class PlayerAliveEventArgs : EventArgs 
{ 
    public bool Alive { get; set; } 

    public PlayerAliveEventArgs(bool deadOrAlive) 
    { 
     Alive = deadOrAlive; 
    } 
} 

我扎的方法來該事件...

public void Form_Load() 
{ 
    game.GameOver += Form1_GameOverMethod; // it shows the error here. 
    it says no overload of this method matches System.Eventhandler 
} 

public void Form1_GameOverMethod(object sender, PlayerAliveEventArgs e) 
{ 
    if (!e.Alive) 
    { 
     GameTimer.Enabled = false; 
     gameOver = true; 
     Refresh(); 
    } 
} 

該錯誤是:

方法在此上下文中不存在。

這是爲什麼?

好吧,我做了以下修改:

public void Form1_GameOverMethod(object sender, EventArgs e) 
{ 
     PlayerAliveEventArgs d = (PlayerAliveEventArgs)e; 
     if (!d.Alive) 
     { 
     } 
} 

是它現在沒事了?還是會解僱一些問題,當我運行它(我想拯救自己的調試後..)

+0

操作(+ =)這裏增加了一個事件處理方法到對象的事件。 – 2011-04-13 14:03:48

回答

0

GameOverMethod實際上並不存在。然而,存在什麼(並且這是你想要的我想)是Form1_GameOverMethod

還有一些言論。首先,在發起活動之前,您應該檢查是否有人訂閱了該活動。

if(GameOver!=null) 
    GameOver(this, new PlayerAliveEventArgs(Alive)); 

第二,我相信你應該改變你的事件聲明是:

public event EventHandler<PlayerAliveEventArgs> GameOver; 

希望這有助於

+0

真棒,我didnt知道..但我不需要考慮你的第一個事件,導致訂閱發生儘快當表單加載自己。 game.GameOver + = Form1_GameOverMethod位於Form1_Load事件處理程序 – 2011-04-13 14:15:44

+0

內部,在這種情況下可能爲true,但您應該採取這些預防措施以避免在其他情況下出現奇怪的例外。 – AbdouMoumen 2011-04-13 14:27:33

4

事件聲明:

public event EventHandler<PlayerAliveEventArgs> GameOver; 

訂閱:

game.GameOver += Form1_GameOverMethod; 

事件處理程序:

private void Form1_GameOverMethod(object sender, PlayerAliveEventArgs e) 
{ 
    bool alive = e.Alive; 
} 

發射:

if (this.GameOver != null) // does any subscriber exist? 
{ 
    this.GameOver(this, new new PlayerAliveEventArgs(..)); 
} 
+0

但是當我添加它。它告訴我沒有重載方法匹配System.EventHandler ..爲什麼? – 2011-04-13 14:02:57

+0

@Dmitry:我更新了我的答案 – abatishchev 2011-04-13 14:05:56

+0

您必須更改您的活動的代表以匹配Form1_GameOverMethod ..我相信您需要閱讀有關創建活動的信息... – 2011-04-13 14:06:09

1

您應該使用

game.GameOver += Form1_GameOverMethod; 
1

因爲你的方法被命名爲Form1_GameOverMethod