i have an error when creating an event
i have the following:
a game class
class Game
{
public event EventHandler GameOver;
public void go()
{
PlayerAliveEventArgs playerAlive = new PlayerAliveEventArgs(Alive);
GameOver(this, playerAlive);
}
}
then i have a class
public class PlayerAliveEventArgs : EventArgs
{
public bool Alive { get; set; }
public PlayerAliveEventArgs(bool deadOrAlive)
{
Alive = deadOrAlive;
}
}
in 开发者_C百科another class i tie a method to the event...
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();
}
}
The error is:
Method doesn't exist in this context.
Why is that?
okay i made the following changes:
public void Form1_GameOverMethod(object sender, EventArgs e)
{
PlayerAliveEventArgs d = (PlayerAliveEventArgs)e;
if (!d.Alive)
{
}
}
is it okay now? or will it fire some problems when i run it (i want to save myself debugging latter on..)
Event declaration:
public event EventHandler<PlayerAliveEventArgs> GameOver;
Subscription:
game.GameOver += Form1_GameOverMethod;
Event handler:
private void Form1_GameOverMethod(object sender, PlayerAliveEventArgs e)
{
bool alive = e.Alive;
}
Firing:
if (this.GameOver != null) // does any subscriber exist?
{
this.GameOver(this, new new PlayerAliveEventArgs(..));
}
You should use
game.GameOver += Form1_GameOverMethod;
Because you method is named Form1_GameOverMethod
.
GameOverMethod
doesn't exist in that context indeed. what exists however (and that's what you intended I suppose) is Form1_GameOverMethod
.
A couple more remarks. First, before firing an event, you should check whether someone has subscribed to it or not.
if(GameOver!=null)
GameOver(this, new PlayerAliveEventArgs(Alive));
Second, I believe you should change you event declaration to be:
public event EventHandler<PlayerAliveEventArgs> GameOver;
Hope this helps
精彩评论