开发者

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

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 button click, in the subscriber method, there is always "EventArgs e" parameter. Can I create somehow the method that will pass data this way, I mean they will be passed in the base Eventargs?


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜