假设我有一个名为Frog的类,它看起来像:
public class Frog
{
public int Location { get; set; }
public int JumpCount { get; set; }
public void OnJump()
{
JumpCount++;
}
}
Run Code Online (Sandbox Code Playgroud)
我需要两件事的帮助:
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)
以下是如何使用普通 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)