C# event with custom arguments

前端 未结 7 1534
庸人自扰
庸人自扰 2020-12-05 09:29

I want to have an event that takes an enum only as the argument. For example

public enum MyEvents{
   Event1
}

// how do I declare this to take enum MyEvent         


        
7条回答
  •  星月不相逢
    2020-12-05 09:51

    Here's a reworking of your sample to get you started.

    • your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.

    • the sample below also uses the more standard naming OnXxx for the method that raises the event.

    • the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.

    .

    public enum MyEvents{ 
         Event1 
    } 
    
    public class MyEventArgs : EventArgs
    {
        public MyEventArgs(MyEvents myEvents)
        {
            MyEvents = myEvents;
        }
    
        public MyEvents MyEvents { get; private set; }
    }
    
    public static class MyClass
    {
         public static event EventHandler EventTriggered; 
    
         public static void Trigger(MyEvents myEvents) 
         {
             OnMyEvent(new MyEventArgs(myEvents));
         }
    
         protected static void OnMyEvent(MyEventArgs e)
         {
             if (EventTriggered != null)
             {
                 // Normally the first argument (sender) is "this" - but your example
                 // uses a static event, so I'm passing null instead.
                 // EventTriggered(this, e);
                 EventTriggered(null, e);
             } 
         }
    }
    

提交回复
热议问题