1
我試着去實施一個遊戲,有一些能觸發或處理事件wheter與否,他們實現這些接口的類的事件系統:如何實現事件系統
public interface IGameEvent<T> where T : EventArgs
{
event EventHandler<T> OnEvent;
}
public interface IGameHandler<T> where T : EventArgs
{
void OnEvent(object sender, T e);
}
一切看起來很棒,直到我意識到,類可以實現超過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;
}
}
KeyPressEvent:
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));
}
}
會更好的suscribers手動存儲在的EventSystem列表?
比這種方法要慢多少還是更快?
謝謝!