开发者

C# Events without arguments. How do I handle them?

I'm currently working on a menu system for a game and I have the standard hierarchy for screens and screen elements. (Screens contain some collection of screen elements). I'd like screen elements to send an event to the screen class to declare that it's been selected. However, I don't need any event arguments in this case. I'm not sure what the syntax is to create the event without any arguments. I found a solution that passes the player index as an event argument. (My game is strictly single-player, so this is not necessary.)

public event EventHandler<PlayerIndexEventArgs> Selected;

^-- How this event is declared where PlayerIndexEventArgs inherits fr开发者_如何学Goom EventArgs. Can I omit PlayerIndexEventArgs, or is there a default type to use here to send no arguments? (Maybe just the EventArgs base class?)


You can use Action delegates. This is much more elegantly then using data you will never need (I mean EventArgs).

Here you define events:

public event Action EventWithoutParams;
public event Action<int> EventWithIntParam;

And here you fire events:

EventWithoutParams();
EventWithIntParam(123);

You can find all the information you need at Action or Action<T>.

Either of these events can be initialised with a no-op delegate ... = delegate { }; so that you don't need to check for null before firing the event.


Try:

public event EventHandler Selected;

then to call..

Selected(null, EventArgs.Empty);

This way it's the default event definition and you don't need to pass any information if you don't want to.


You can just write:

public event EventHandler Selected;


(Maybe just the EventArgs base class?)

You should do exactly that.

From the MSDN Docs on EventArgs:

This class contains no event data; it is used by events that do not pass state information to an event handler when an event is raised.


Going by the PlayerIndexEventArgs type you mentioned, I am assuming you are using XNA, right? If so, take a look at the Game State Management sample. If not the code might help you understand how to do it anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜