2011-04-13 7 views
0

を作成する際に、私は、次ている:私は方法を結ぶiは誤差を有するイベント

ゲームクラス

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

演算子(+ =)はここにあなたのオブジェクトのイベントにイベントハンドラメソッドを追加することができます。 –

答えて

0

GameOverMethod実際にはこのような状況には存在しません。しかし、何が存在するのか(それはあなたが私が想定したものです)はForm1_GameOverMethodです。

カップル以上の発言。まず、イベントを発生させる前に、誰かがそれに加入しているかどうかを確認する必要があります。

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

第二に、私はあなたがするあなたのイベント宣言を変更する必要があります信じる:

public event EventHandler<PlayerAliveEventArgs> GameOver; 

ホープこれは

+0

素晴らしい、私はそれを知っていません..しかし、私はあなたの最初のイベントを考慮する必要はありません、フォーム自体がロードされるためです。 game.GameOver + = Form1_GameOverMethodはForm1_Loadイベントハンドラー –

+0

の中にありますが、この場合には当てはまりますが、他のシナリオでは奇妙な例外を避けるためにこれらの予防策を講じてください。 – AbdouMoumen

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にマッチするメソッドへのオーバーロードはありません。なぜですか? –

+0

@ドミトリー:私の回答を更新しました – abatishchev

+0

イベントの代理人をForm1_GameOverMethodに合わせて変更する必要があります。イベントの作成について読む必要があると思います... –

1

あなたの方法をForm1_GameOverMethod命名されているのであなたは

game.GameOver += Form1_GameOverMethod; 
1

を使用する必要があります。