C# - Create an EventHandler that can take any number of parameters

后端 未结 3 1366
孤街浪徒
孤街浪徒 2021-02-08 03:07

I wish to create a custom EventHandler that can have any number of objects as its parameters and the objects it gets isn\'t known in advance.

I know I can pass it an Obj

相关标签:
3条回答
  • 2021-02-08 03:43

    There's nothing to stop you declaring a delegate that accepts a params array, the same as you would define any other method which takes multiple arguments:

    delegate void someCustomEvent(params object[] args);
    
    event someCustomEvent sce;
    

    However, it would be unusual. As Kent says, it's more normal to follow the convention on the .Net platform of having event handlers accepting two arguments, the sender (object), and the event arguments (EventArgs, or something deriving from it).

    0 讨论(0)
  • 2021-02-08 03:44

    EventHandler is just a delegate.

    You can create delegate like this:

    public delegate void Foo(params object[] args);
    

    And event:

    public event Foo Bar;
    

    You will end up with firing event like this:

    Bar(1, "");
    

    But, as @Kent Boogaart said, you should create events using EventHandler<TEventArgs>, so better approach would be creating class:

    public class MyEventArgs : EventArgs
    {
        public MyEventArgs(params object[] args)
        {
            Args = args;
        }
    
        public object[] Args { get; set; }
    }
    

    And event:

    public event EventHandler<MyEventArgs> Bar2;
    

    So you will fire event like this:

    Bar2(this, new MyEventArgs(1, ""));
    
    0 讨论(0)
  • You can define a delegate as such:

    public delegate void MyHandler(object p1, object p2, object p3);
    

    and then use it in your event definition:

    public event MyHandler MyEvent;
    

    However, this is contrary to best practices and not recommended. Instead, you should encapsulate all the extra information you require into your own EventArgs subclass and use that from your delegate:

    public class MyEventArgs : EventArgs
    {
        // any extra info you need can be defined as properties in this class
    }
    
    public event EventHandler<MyEventArgs> MyEvent;
    
    0 讨论(0)
提交回复
热议问题