How to add an event to a class

前端 未结 2 969
遇见更好的自我
遇见更好的自我 2020-12-08 03:50

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

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


     publi         


        
相关标签:
2条回答
  • 2020-12-08 04:40
    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!");
    }
    
    0 讨论(0)
  • 2020-12-08 04:43

    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)

    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.

    public event EventHandler Jump = delegate { };
    
    public void OnJump()
    {
        Jump(this, EventArgs.Empty);
    }
    
    0 讨论(0)
提交回复
热议问题