1

我正在构建游戏并尝试使用事件系统。这是它如何实现的主要思想:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blocker2
{
    public delegate void OnPlayerMoved(PlayerMovedEvent e);
    public delegate void OnPlayerSpawned(PlayerSpawnedEvent e);
    public delegate void OnBlockBreak(BlockBreakEvent e);
    public delegate void OnBlockPlaced(BlockPlacedEvent e);

    public static class EventHandler
    {
        private static List<OnPlayerMoved> _onPlayerMoved;
        private static List<OnPlayerSpawned> _onPlayerSpawned;
        private static List<OnBlockBreak> _onBlockBreak;
        private static List<OnBlockPlaced> _onBlockPlaced;


        static EventHandler()
        {

        }

        public static void Subscribe()
        {

        }

        // -------------------------- Player Related Events --------------------------
        public static void OnPlayerMoved(PlayerMovedEvent e)
        {
            foreach (OnPlayerMoved del in _onPlayerMoved)
            {
                del(e);
            }
        }

        public static void OnPlayerSpawned(PlayerSpawnedEvent e)
        {
            foreach (OnPlayerSpawned del in _onPlayerSpawned)
            {
                del(e);
            }
        }

        // -------------------------- Block Related Events --------------------------
        public static void OnBlockBreak(BlockBreakEvent e)
        {
            foreach (OnBlockBreak del in _onBlockBreak)
            {
                del(e);
            }
        }

        public static void OnBlockPlaced(BlockPlacedEvent e)
        {
            foreach (OnBlockPlaced del in _onBlockPlaced)
            {
                del(e);
            }
        }
    }
}

而且还会有更多的事件发生,我认为这种方法会使代码变得非常非常复杂。有更好的方法吗?(考虑代码的性能和可维护性)。提前致谢!对不起,我的英语不好。

4

1 回答 1

4

为什么不使用标准C# 事件?他们将以相同的方式处理此问题,因为一个事件允许多个订阅者。

C# 中的标准事件机制允许多个订阅者订阅一个事件,如下所示:

public static event EventHandler<PlayerMovedEventArgs> PlayerMoved;

// Often, you'll have a method to raise the event:
public static void OnPlayerMoved(PlayerMovedEventArgs args)
{
    var handler = PlayerMoved;
    if (handler != null)
        handler(null, args);
}

话虽如此,我建议将它们放入它们相关的类中,而不是让它们全部是全局/静态的。然后,您可以潜在地使该方法引发该类的私有事件,这将允许您使设计更易于维护。

例如,该PlayerMoved事件可能更适合代表您的世界(或世界的一部分)的某个类,并且以非静态方式存在。

于 2013-05-06T16:14:29.087 回答