It is possible to pass data to EventArgs without creating derived class?

前端 未结 3 1101
梦如初夏
梦如初夏 2021-02-19 07:27

I am a bit confused. I know I can create class derived from EventArgs in order to have custom event data. But can I employ the base class EventArgs somehow? Like the mouse butto

相关标签:
3条回答
  • 2021-02-19 08:23

    Is it possible to just use the EventArgs datatype raw? Absolutely. According to MSDN:

    This class contains no event data; it is used by events that do not pass state information to an event handler when an event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data.

    http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

        private event TestEventEventHandler TestEvent;
        private delegate void TestEventEventHandler(EventArgs e);
    
        private void button1_Click(object sender, EventArgs e)
        {
            TestEvent += TestEventHandler;
            if (TestEvent != null)
            {
                TestEvent(new EventArgs());
            }
        }
        private void TestEventHandler(EventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("hi");
        }
    

    Should you ever do it? Not for any reason I can think if. If you want to create your own clicks you can just instantiate the MouseEventArgs on your own, too:

    MouseEventArgs m = new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 42, 42, 1);
    
    0 讨论(0)
  • 2021-02-19 08:24

    You can use the EventArgs class through the Generic Types approach. In this sample, i will use the Rect class with as return type:

    public EventHandler<Rect> SizeRectChanged;
    

    Raising the event:

    if(SizeRectChanged != null){
       Rect r = new Rect(0,0,0,0);
       SizeRectChanged(this,r);
    }
    

    Listening the event:

    anyElement.SizeRectChanged += OnSizeRectChanged;
    
    public void OnSizeRectChanged(object sender, Rect e){
        //TODO abything using the Rect class
        e.Left = e.Top = e.Width = e.Height = 50;
    }
    

    So, don't need to create new events classes or delegates, simply create a EventHandler passing the specific type T.

    0 讨论(0)
  • 2021-02-19 08:30

    Nope. The EventArgs base class is just a way to allow for some standard event delegate types. Ultimately, to pass data to a handler, you'll need to subclass EventArgs. You could use the sender arg instead, but that should really be the object that fired the event.

    0 讨论(0)
提交回复
热议问题