我在创建活动时遇到错误

时间:2011-04-13 13:58:31

标签: c# .net winforms events event-handling

我有以下内容:

游戏类

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)
      {
      }
 }

现在好吗?或者它会在我运行它时发出一些问题(我想保存自己调试后者......)

4 个答案:

答案 0 :(得分: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(..));
}

答案 1 :(得分:1)

你应该使用

game.GameOver += Form1_GameOverMethod;

答案 2 :(得分:1)

因为您的方法名为Form1_GameOverMethod

答案 3 :(得分:0)

GameOverMethod确实不存在于该上下文中。然而,存在的是什么(这是你想要的)Form1_GameOverMethod

还有几个评论。首先,在触发事件之前,您应该检查是否有人订阅了它。

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

其次,我相信您应该将事件声明更改为:

public event EventHandler<PlayerAliveEventArgs> GameOver;

希望这有帮助

相关问题