如何将事件添加到班级

时间:2020-03-05 18:59:21  来源:igfitidea点击:

假设我有一个名为Frog的类,它看起来像:

public class Frog
{
     public int Location { get; set; }
     public int JumpCount { get; set; }

     public void OnJump()
     {
         JumpCount++;
     }

}

我需要2件事的帮助:

  • 我想在类定义中创建一个名为Jump的事件。
  • 我想创建Frog类的实例,然后创建另一个在Frog跳转时将被调用的方法。

解决方案

回答

public event EventHandler Jump;
public void OnJump()
{
    EventHandler handler = Jump;
    if (null != handler) handler(this, EventArgs.Empty);
}

然后

Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);

private void yourMethod(object s, EventArgs e)
{
     Console.WriteLine("Frog has Jumped!");
}

回答

@CQ:为什么要创建"跳转"的本地副本?此外,我们可以通过稍微更改事件的声明来保存后续测试:

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}