简体   繁体   English

通用EventArgs和扩展方法

[英]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: 因为我需要向事件传递一些参数,所以我认为我将创建通用的EventArgs类:

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? 1.如何修改我的扩展方法以能够如下调用我的事件?

TestEvent.Fire(...);

2.Is it good practise to extend events and then write extension methods to them this way? 2.扩展事件然后以这种方式为事件编写扩展方法是一种好习惯吗?

  1. You don't need to modify anything, your extension method should work fine with generic EventArgs<T> . 您无需进行任何修改,您的扩展方法应该可以与通用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"}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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