C# C语言中的委托运动#

C# C语言中的委托运动#,c#,C#,有没有人能解释一下//TBD中的问题,或者给我举一些例子说明这是如何工作的?我理解一些,如果它有点,但我仍然有任何我尝试的问题 namespace DelgateKeypress { class Program { private static int x=20; private static int y=20; //TBD: You will need to define a data structure to store the association

有没有人能解释一下//TBD中的问题,或者给我举一些例子说明这是如何工作的?我理解一些,如果它有点,但我仍然有任何我尝试的问题

  namespace DelgateKeypress
 {
class Program
{
    private static int x=20;
    private static int y=20;

    //TBD: You will need to define a data structure to store the association 
    //between the KeyPress and the Action the key should perform


    private static void Main(string[] args)
    {
        //TBD: Set up your control scheme here. It should look something like this:
        //   myControls.Add(ConsoleKey.W, Up)
        //   myControls.Add(ConsoleKey.S, Down)
        //or you can ask the user which keys they want to use
        //etc





        while (true)
        {
            Console.SetCursorPosition(x, y);
            Console.Write("O");

            var key = Console.ReadKey(true);


            int oldX = x;
            int oldY = y;


            //TBD: Replace the following 4 lines by looking up the key press in the data structure
            //and then performing the correct action
            if (key.Key == ConsoleKey.W) Up();
            if (key.Key == ConsoleKey.S) Down();
            if (key.Key == ConsoleKey.A) Left();
            if (key.Key == ConsoleKey.D) Right();

            Console.SetCursorPosition(oldX, oldY);
            Console.Write(".");


        }
    }

    private static void Right()
    {
        x++;
    }

    private static void Left()
    {
        x--;
    }

    private static void Down()
    {
        y++;
    }

    private static void Up()
    {
        y--;
    }
}
}


我有点理解这一点,但我很难让用户能够输入他们想要为上、下、左和右的每个关键动作添加的值。我不必让这种情况发生,这些动作可能只是W、S、A、D,但我在这里不知所措,所以任何帮助都是很棒的。这是一门课的作业吗?如果是这样的话,你一定要跟你的老师联系,让他们更详细地解释为什么给你这个作业,你应该如何完成它,并确保你从练习中得到了老师想要的东西。同时


在我看来,根据注释中提供的示例语法(例如,
myControls.Add(ConsoleKey.W,Up)
),这些注释的作者希望您声明一个
字典,填充它,然后在按下键时使用它

声明如下:

static Dictionary<ConsoleKey, Action> myControls;
myControls = new Dictionary<ConsoleKey, Action>
{
    { ConsoleKey.W, Up },
    { ConsoleKey.S, Down },
    { ConsoleKey.A, Left },
    { ConsoleKey.D, Right },
};
myControls[key.Key]();
或者,如果可能存在数据结构中不存在的键值(在您的示例中似乎是这样):


词典
上搜索文档。那会有帮助的。
Action action;

if (myControls.TryGetValue(key.Key, out action))
{
    action();
}