没有参数的C#事件如何处理? [英] C# Events without arguments. How do I handle them?

查看:101
本文介绍了没有参数的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?)

推荐答案

可以使用Action代理。这是非常优雅的,然后使用你永远不需要的数据(我的意思是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;

在这里你点火事件:

EventWithoutParams();
EventWithIntParam(123);

您可以在 Action Action< T>

这些事件中的任何一个都可以使用no-op委托进行初始化 ... = delegate {}; ,以便在触发事件之前不需要检查null。

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天全站免登陆