如何向类中添加事件 [英] How to add an event to a class

查看:118
本文介绍了如何向类中添加事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have a class named Frog, it looks like:

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


     public void OnJump()
     {
         JumpCount++;
     }

}



我需要帮助2件事:

I need help with 2 things:


  1. 我想在类定义中创建一个名为Jump的事件。

  2. 一个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!");
}

这篇关于如何向类中添加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆