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

后端 未结 3 1369
孤街浪徒
孤街浪徒 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: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, 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 Bar2;
    

    So you will fire event like this:

    Bar2(this, new MyEventArgs(1, ""));
    

提交回复
热议问题