C#事件不带参数。我该如何处理? [英] C# Events without arguments. How do I handle them?

查看:131
本文介绍了C#事件不带参数。我该如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对游戏的菜单系统和我有屏幕和屏幕元素的标准层次结构。 (屏幕包含屏幕元素的一些集合)。我想屏幕元素将事件发送到屏幕类,宣布它被选中。不过,我并不需要在这种情况下,任何事件参数。我不知道语法是不带任何参数创建活动的内容。我发现,通过玩家指数作为事件参数的解决方案。 (我的比赛是严格单一的球员,所以这是没有必要的。)

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;



^ - 如何声明此事件,其中PlayerIndexEventArgs继承于EventArgs。我可以省略PlayerIndexEventArgs,或者是有利用这里给无参数的默认类型? (也许只是EventArgs的基类?)

^-- How this event is declared where PlayerIndexEventArgs inherits from EventArgs. Can I omit PlayerIndexEventArgs, or is there a default type to use here to send no arguments? (Maybe just the EventArgs base class?)

推荐答案

您可以使用动作委托。这是更优雅然后用你不需要的数据(我指的EventArgs)

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

在这里定义事件:

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



在这里你触发事件:

And here you fire events:

EventWithoutParams();
EventWithIntParam(123);

您可以找到您需要的动作动作< T>

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.

这篇关于C#事件不带参数。我该如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆