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

萝らか妹 提交于 2019-12-04 11:05:43

问题


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 Object[] but what I would like is something similar to

MyEventHandler someCustomEvent(Object obj1, Object obj2, Object obj3)

where the number of objects can be 0 or 10 if needed.

EDIT:

So thanks to the comments and answers I've got I've come to this,

public class FinishedEventArgs : EventArgs {
            public Object[] Args{ get; set; }
        }

protected void OnFinished(params Object[] args) {
            if(this.Finished != null) {
                this.Finished(this, new FinishedEventArgs() {
                    Args = args
                });
            }
        }

Does it look acceptable?


回答1:


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, ""));



回答2:


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;



回答3:


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).



来源:https://stackoverflow.com/questions/3994666/c-sharp-create-an-eventhandler-that-can-take-any-number-of-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!