0

在我的 C#/XNA 项目中,我有一个管理输入的“静态”类。它看起来像这样:

internal sealed class InputManager
{
    public delegate void KeyboardHandler(Actions action);

    public static event KeyboardHandler KeyPressed;

    private static readonly Dictionary<Actions, Keys> KeyBindings = Main.ContentManager.Load<Dictionary<Actions, Keys>>("KeyBindings");

    private static KeyboardState currentKeyboardState;

    private InputManager()
    {
    }

    public static void GetInput()
    {
        currentKeyboardState = Keyboard.GetState();

        foreach (KeyValuePair<Actions, Keys> actionKeyPair in KeyBindings)
        {
            if (currentKeyboardState.IsKeyDown(actionKeyPair.Value))
            {
                OnKeyPressed(actionKeyPair.Key);
            }
        }
    }

    private static void OnKeyPressed(Actions action)
    {
        if (KeyPressed != null)
        {
            KeyPressed(action);
        }
    }
}

因此,在整个游戏过程中,我获取输入并检查当前是否按下了字典中包含的任何键(我使用字典进行键绑定——一个动作绑定到一个键)。如果是这样,KeyPressed 事件将被触发,并将关联的操作作为参数。通过这样做,我可以为这个事件订阅一个外部类(例如相机)并根据动作(键)做适当的事情。

问题是我必须像这样测试每个订阅者的方法中的操作:

        if (action == Actions.MoveLeft)
        {
            DoSomething();
        }

因此,无论按下哪个键(只要它是字典的一部分),每个订阅者的方法都会被调用,即使它实际上不需要。

我知道我可以为每个操作设置一个事件:事件 MoveLeft、事件 MoveRight 等……但是,有没有更好的方法来执行此操作,例如事件列表?

4

1 回答 1

0

您可以使用接口来处理:例如:

interface IExecuteAction
{
void doMoveLeftAction();
void doMoveRightAction(); 
}

ExecuteMoveLeftAction(Actions action,IExecuteAction execAction)
{
switch(action
 case Actions.MoveLeft :
        execAction.doMoveLeftAction(); 
        break; 
case Actions.MoveLeft :
        execAction.doMoveLeftAction(); 
        break;
}

在您的代码中在您的订阅者上实现此接口

class subscriber1:IExecuteAction
{
void doMoveLeftAction()
{
//do what you want
}
void doMoveRightAction()
 {
 //do what you want
 }
}

在你这样处理之后:

ExecuteMoveLeftAction(action,subscriber1);
于 2012-08-12T01:25:23.707 回答