C# 如何将事件添加到类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/85137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:24:47  来源:igfitidea点击:

How to add an event to a class

提问by public static

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

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

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


     public void OnJump()
     {
         JumpCount++;
     }

}

I need help with 2 things:

我需要两件事的帮助:

  1. I want to create an event named Jump in the class definition.
  2. I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
  1. 我想在类定义中创建一个名为 Jump 的事件。
  2. 我想创建一个Frog类的实例,然后再创建一个在Frog跳跃时会调用的方法。

采纳答案by Quintin Robinson

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

then

然后

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

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

回答by Konrad Rudolph

@CQ: Why do you create a local copy pf Jump? Additionally, you can save the subsequent test by slightly changing the declaration of the event:

@CQ:为什么要创建本地副本 pf Jump?此外,您可以通过稍微更改事件的声明来保存后续测试:

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}

回答by Tezra

Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that ?.is used instead of .to insure that if the event is null, it will fail cleanly (return null)

以下是如何使用普通 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);
}

Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution.

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

public event EventHandler Jump = delegate { };

public void OnJump()
{
    Jump(this, EventArgs.Empty);
}