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

前端 未结 5 1316
无人及你
无人及你 2020-12-30 23:35

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

相关标签:
5条回答
  • 2020-12-31 00:23

    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.

    0 讨论(0)
  • 2020-12-31 00:31

    You can just write:

    public event EventHandler Selected;
    
    0 讨论(0)
  • 2020-12-31 00:32

    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.

    0 讨论(0)
  • 2020-12-31 00:35

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

    0 讨论(0)
  • 2020-12-31 00:39

    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 讨论(0)
提交回复
热议问题