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

前端 未结 3 1128
梦如初夏
梦如初夏 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);
    

提交回复
热议问题