题
假设我有一个名为 Frog 的类,它看起来像:
public class Frog
{
public int Location { get; set; }
public int JumpCount { get; set; }
public void OnJump()
{
JumpCount++;
}
}
我需要两件事的帮助:
- 我想在类定义中创建一个名为 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:为什么要创建本地副本 pf Jump
?另外,您可以通过稍微更改事件的声明来保存后续测试:
public event EventHandler Jump = delegate { };
public void OnJump()
{
Jump(this, EventArgs.Empty);
}
以下是如何使用普通 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);
}
请注意,只有在没有订阅者的情况下,事件本身才为 null,并且一旦调用,该事件就是线程安全的。因此,您还可以分配一个默认的空处理程序以确保事件不为空。请注意,从技术上讲,这很容易被其他人清除所有事件(使用 GetInitationList),因此请谨慎使用。
public event EventHandler Jump = delegate { };
public void OnJump()
{
Jump(this, EventArgs.Empty);
}
不隶属于 StackOverflow