如何将事件添加到类中

pub*_*tic 40 c# events class

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

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


     public void OnJump()
     {
         JumpCount++;
     }

}
Run Code Online (Sandbox Code Playgroud)

我需要两件事的帮助:

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

Qui*_*son 60

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

然后

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

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

  • 这是为了避免在处理器为空的时间和调用处理程序的实际时间之间的c#中的死处理程序..该方法可能已被删除.因此,您设置对处理程序当前指向的位置的引用,然后在该引用上检查null并调用. (9认同)
  • @publicstatic关于EventHandler handler = Jump; 现在(2015)可以缩短为 Jump?.Invoke(this, EventArgs.Empty); 请参阅:/sf/ask/1984645071/ (4认同)

Tez*_*zra 6

以下是如何使用普通 EventHandler 或自定义委托的示例。请注意,?.用于.确保如果事件为空,它将完全失败(返回空)

public delegate void MyAwesomeEventHandler(int rawr);
public event MyAwesomeEventHandler AwesomeJump;

public event EventHandler Jump;

public void OnJump()
{
    AwesomeJump?.Invoke(42);
    Jump?.Invoke(this, EventArgs.Empty);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果没有订阅者,则事件本身仅为 null,并且一旦被调用,该事件就是线程安全的。因此,您还可以分配一个默认的空处理程序以确保事件不为空。请注意,这在技术上容易受到其他人清除所有事件(使用 GetInvocationList)的影响,因此请谨慎使用。

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}
Run Code Online (Sandbox Code Playgroud)