C# 如何实现事件系统
我正在尝试为游戏实现一个事件系统,其中有一些类可以触发或处理事件,无论它们是否实现这些接口:C# 如何实现事件系统,c#,performance,event-handling,C#,Performance,Event Handling,我正在尝试为游戏实现一个事件系统,其中有一些类可以触发或处理事件,无论它们是否实现这些接口: public interface IGameEvent<T> where T : EventArgs { event EventHandler<T> OnEvent; } public interface IGameHandler<T> where T : EventArgs { void OnEvent(object sender, T e);
public interface IGameEvent<T> where T : EventArgs
{
event EventHandler<T> OnEvent;
}
public interface IGameHandler<T> where T : EventArgs
{
void OnEvent(object sender, T e);
}
公共接口IGameEvent,其中T:EventArgs
{
事件处理程序OnEvent;
}
公共接口IGameHandler,其中T:EventArgs
{
void OnEvent(对象发送者,te);
}
一切看起来都很棒,直到我意识到没有一个类可以实现超过1个IGameEvent
因为会造成重复申报,
以下是一个例子:
public class Event
{
public KeyPressEvent OnKeyPress;
public UpdateEvent OnUpdate;
public void AddHadler<T>(IGameEvent<T> eEvent , IGameHandler<T> eHandler) where T : EventArgs
{
eEvent.OnEvent += eHandler.OnEvent;
}
public void RemoveHandler<T>(IGameEvent<T> eEvent, IGameHandler<T> eHandler) where T : EventArgs
{
eEvent.OnEvent -= eHandler.OnEvent;
}
}
公共类事件
{
按键上的公共按键事件;
公共更新事件更新;
public void AddHadler(IGameEvent eEvent,IGameHandler),其中T:EventArgs
{
eEvent.OnEvent+=eHandler.OnEvent;
}
public void RemoveHandler(IGameEvent eEvent,IGameHandler),其中T:EventArgs
{
eEvent.OnEvent-=eHandler.OnEvent;
}
}
按键事件:
public class KeyPressEvent : IGameEvent<KeyPressEvent.KeyPressedEventArgs>
{
public class KeyPressedEventArgs : EventArgs
{
public KeyPressedEventArgs(Keys key)
{
Key = key;
}
public Keys Key { get; private set; }
}
public event EventHandler<KeyPressedEventArgs> OnEvent;
private void OnCheckForKeyPressed() //Example
{
if (OnEvent != null)
OnEvent(this, new KeyPressedEventArgs(Keys.Space));
}
}
public class按键事件:IGameEvent
{
public class KeyPressedEventArgs:EventArgs
{
公钥按Eventargs(按键)
{
钥匙=钥匙;
}
公钥密钥{get;private set;}
}
公共事件处理程序;
private void oncheckworkypressed()//示例
{
if(OnEvent!=null)
OnEvent(这个,新的KeyPressedEventArgs(Keys.Space));
}
}
在EventSystem中手动将使用者存储在列表中会更好吗
比这种方法慢或快多少
谢谢 常用的方法是实现事件聚合器模式。谷歌搜索将为您提供大量不同的变体。例如,它可能看起来像这样(我目前正在使用的):
接口IEventsagGator
{
//激发一个事件,由特定消息重新呈现
无效发布(TMessage消息);
//将对象添加到订阅服务器列表中
void订阅(对象侦听器);
//从订阅服务器列表中删除对象
无效取消订阅(对象侦听器);
}
接口IHandler
{
//在订阅服务器中实现此功能以处理特定消息
无效句柄(TMessage消息);
}
常用的方法是实现事件聚合器模式。谷歌搜索将为您提供大量不同的变体。例如,它可能看起来像这样(我目前正在使用的):
接口IEventsagGator
{
//激发一个事件,由特定消息重新呈现
无效发布(TMessage消息);
//将对象添加到订阅服务器列表中
void订阅(对象侦听器);
//从订阅服务器列表中删除对象
无效取消订阅(对象侦听器);
}
接口IHandler
{
//在订阅服务器中实现此功能以处理特定消息
无效句柄(TMessage消息);
}
interface IEventsAggrgator
{
//fires an event, reperesented by specific message
void Publish<TMessage>(TMessage message);
//adds object to the list of subscribers
void Subscribe(object listener);
//remove object from the list of subscribers
void Unsubscribe(object listener);
}
interface IHandler<TMessage>
{
//implement this in subscribers to handle specific messages
void Handle(TMessage message);
}