简体   繁体   中英

Generic EventArgs and extension method

I was looking over the internet for a way to fire events easier and I found this extension class:

public static class EventExtensions
{
    public static void Fire<TEventArgs>(this EventHandler<TEventArgs> @event, object sender, TEventArgs e)
        where TEventArgs : EventArgs
    {
        if (@event != null)
            @event(sender, e);
    }
}

This allows me to fire event using

TestEvent.Fire(this,new CallEventArgs(1,"OK"));

instead of

if(TestEvent != null)
    TestEvent(this, new CallEventArgs(1,"OK"));

Because I need to pass some arguments to my events I thought I will create generic EventArgs class:

public class EventArgs<T> : EventArgs
{
    public EventArgs()
    {
        Value = default(T);
    }

    public EventArgs(T aValue)
    {
        Value = aValue;
    }

    public T Value { get; set; }
}

With this I can declare my event as:

public event EventHandler<EventArgs<MyClass>> TestEvent; 

and fire it with:

if(TestEvent != null)
    TestEvent(this, new EventArgs<MyClass>(new MyClass{Id = 1, Description = "OK"}));

My questions are:

1.How should I modify my extension method to be able to call my event as below?

TestEvent.Fire(...);

2.Is it good practise to extend events and then write extension methods to them this way?

  1. You don't need to modify anything, your extension method should work fine with generic EventArgs<T> .

  2. This approach is fine, there's nothing wrong about it.

  3. You may want to add the following overload:

     public static void Fire<T> (this EventHandler<EventArgs<T>> @event, object sender, T value) { if (@event != null) @event(sender, new EventArgs<T>(value)); } 

    This way, you'll be able to fire events like this:

     TestEvent.Fire(sender, new MyClass{Id = 1, Description = "OK"}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM