c# - 如何向类(class)添加事件

标签 c# class events

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

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


     public void OnJump()
     {
         JumpCount++;
     }

}

我需要两件事的帮助:

  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!");
}

关于c# - 如何向类(class)添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/85137/

相关文章:

c# - 传递一个已经启动的基类实例?

java - 在多个类中使用一个对象

java - 从另一个类访问整数值

.net - 如何在 Windows 窗体中模仿 JavaScript 的 onBlur 事件?

javascript - 无法执行内联事件处理程序,因为它违反了内容安全策略指令

c# - 通知模态表单的父级它需要采取一些行动

c# - Xamarin C# - IMKAnnotation 不包含 'x' 的定义

c# - 基于接口(interface)的匿名类型

c# - 从 C# 中杀死 COM 对象

python - 捕获内置异常(而不是自定义异常)