我需要帮助搞清楚这个C#委托关键功能 [英] I need help figuring out this C# delegate key functions

查看:67
本文介绍了我需要帮助搞清楚这个C#委托关键功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个代码的墙上,我需要帮助弄清楚它究竟要求我做什么。我只需要一些如何做到这一点的例子。谢谢



I am at a wall with this code, I need help figuring out what it is exactly asking me to do. I just need some examples of how to do this. Thanks

   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--;
        }
    }
}





主要是TBD部分我不明白它是什么请我做。谢谢



Mainly the TBD parts I Don't understand what it is asking me to do. Thanks

推荐答案

这是你的作业,你应该自己解决。



这里有一些链接提供可能对您有用的信息。



代表(C#编程指南) [ ^ ]



使用代表( C#编程指南) [ ^ ]



代表教程 [ ^ ]
This is your homework and you should solve it by yourself.

Here are some links with information that could be useful for you.

Delegates (C# Programming Guide)[^]

Using Delegates (C# Programming Guide)[^]

Delegates Tutorial[^]


好吧,让我们尝试另一种方式 - 乔治·琼森已经让你走了od信息,但是你可能仍然在试着改头换面..是吗?



在我们看看'TBD'之前,让我们来看看你的节目在做什么当下......



(1)你正在运行一个循环



ok, lets try another way - George Jonsson has given you good info, but you may still be scratching your head going wtf .. yes ?

Before we look at the 'TBD's" lets look at what your program is doing at the moment ...

(1) you're running a loop

while (true)
{
  // Lots of stuff in here 
}





(2)循环中你正在从键盘上读取一个键/字符





(2) in the loop you are reading a key/character from the keyboard

var key = Console.ReadKey(true);





(顺便说一句 - 你知道ReadKey(true)的作用吗?提示 - 看看这里 https://msdn.microsoft.com/en -us / library / x3h8xffw(v = vs.110).aspx [ ^ ])



(3)(深入了解)





(btw - do you know what the ReadKey(true) does ? hint - have a look here https://msdn.microsoft.com/en-us/library/x3h8xffw(v=vs.110).aspx[^] )

(3) (getting to the guts)

if (key.Key == ConsoleKey.W) Up();
if (key.Key == ConsoleKey.S) Down();
if (key.Key == ConsoleKey.A) Left();
if (key.Key == ConsoleKey.D) Right();





所以,如果按下的键是'我们正在调用函数'Up',如果按下的键是's'我们称之为'Down'函数



是吗? ..这有什么不对吗?真的没什么。但是让我们说你想要处理26个键 - 它会是什么样子?





so, if the key pressed is 'w', we are calling the function 'Up', if the key pressed is 's' we call the function 'Down'

Yes ? .. and whats wrong with this ? nothing really. But lets say you wanted to handle 26 keys - what would that look like ?

if (key.Key == ConsoleKey.W) Up();
if (key.Key == ConsoleKey.S) Down();
if (key.Key == ConsoleKey.A) Left();
if (key.Key == ConsoleKey.D) Right();
// More keys
if (key.Key == ConsoleKey.X) DoSomething();
if (key.Key == ConsoleKey.Y) DoSomethingElse();
// Ad nauseum...





正确/专业的程序员会讨厌如果对密钥进行测试的一长串 - 如果您需要添加或删除有效密钥,或更改密钥,或者只是保持代码整洁,那么必须有更好的方法...(在那里冥思马?)



好​​的,那么,你的导师试图引导你走的是一条路径,你可以减少如果键输入等于这个键然后做那个动作那一行



所以,我们将在这里进行一次飞跃..假设我们可以存储所有有效的密钥以及当您在某种商店中推送这些密钥时会发生什么。然后,当你从键盘上获得一个键时,而不是所有那些键,你可能有3行,检查键是否在那种商店中,并执行与键相关的动作



好​​了,所以,现在,轮到你了 - 让我们先看看这个TBD ...





Proper/Professional Programmers would hate a long line of if's testing for the keys - if you needed to add or remove valid keys, or change what keys do, or just keep the code tidy, there must be a better way ... (musnt there ?)

Ok, so, what your instructor is trying to lead you through is a path by which you can reduce the line of 'if key input equals this key then do that action' sort of thing

So, we are going to take a leap here .. lets say we could store all the valid keys and what happens when you push those keys in some kind of store. Then, when you get a key from the keyboard, instead of all those if's, you have maybe 3 lines, to check if the key is in the kind of store, and perform the action associated with the key

ok, so, now, its coming up to your turn - lets look at this first TBD ...

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





您认为我们可以使用哪种数据结构来存储两个值,例如关键,例如a以及我们可能采取的某种行为如果键'a'被按下,想做什么? (..现在,有很多可能的方法可以做到这一点,我想到一个非常明显的方法)...所以看看你的笔记,看看你能想出什么(回复)



What sort of data structure do you think we could use to store two values, such as a 'key' eg 'a' and some sort of action that we might want to do if the key 'a' was pressed ?? (.. now, there are many possible ways to do this, Im thinking of a very obvious one) ... so have a look through your notes, and see what you can come up with (reply back)


我将在George Jonsson和Garth Lancaster的有用答案中添加一些评论。我将专注于使用代表。顺便说一句,许多聪明的人开始使用C#(没有其他语言的背景,相当于'代表存在),很难得到代表们的内容。



委托可以被认为是一个可执行代码单元的模板



所以,如果我们定义: private delegate void KeyCommand(); 实际上,我们已经声明了一个新的'Type,一个原型,一个我们可以从中创建实例的模板我们可以将任何方法插入到...中,只要该方法具有与委托相同的签名 ...这意味着任何返回值和参数的类型必须相同。



在这种情况下,签名是一种不带参数的方法,并且不返回任何内容(无效)。



有些人认为在考虑代表时背诵以下内容是有帮助的:代表是'类型,使用它,我们必须有实例:)



自所有你的光标移动方法有一个与'KeyCommand匹配的签名,其中任何一个都可以用作委托实例的内容。



所以,我们可以写: KeyCommand up = Up; ,然后我们执行up();我们打电话给你的方法,'Up。



使用代理的强大之处在于我们希望在运行时使用可执行代码,我们需要灵活性根据......使用不同的可执行代码。因此,我们可以定义任意数量的委托实例,将它们绑定到与委托签名匹配的方法代码,并灵活使用它们。



我们可以创建一个通用使用委托
I'll add a few comments to the useful answers here by George Jonsson and Garth Lancaster; I'll focus on the use of delegates. By the way, lots of smart people beginning C# (without a background in other languages where the equivalent of 'delegates exists) have trouble "getting" what delegates are about.

A delegate can be thought of as a template for a unit of executable code.

So, if we define: private delegate void KeyCommand(); In effect, we've "declared" a new 'Type, a prototype, a template that we can make instances from into which we can insert any method into ... as long as the method has the same signature as the delegate ... which means that the types of any return value and of parameters must be identical.

In this case, the signature is of a method which takes no parameters, and returns nothing (void).

Some find it helpful to recite the following when thinking of delegates: "The Delegate is a 'Type, to use it, we must have instances" :)

Since all your cursor movement methods have a signature which matches 'KeyCommand, any of them can be used as the "content" of an instance of the delegate.

So, we could write: KeyCommand up = Up;, and then anytime we executed up(); we'd be calling your method, 'Up.

The power of using delegates is when we wish to use executable code at run-time and we need the flexibility of using different executable code depending on ... whatever. So, we can define any number of delegate instances, bind them to method code that matches the signature of the delegate, and use them flexibly.

We can create a generic Dictionary that pairs ConsoleKey values (ConsoleKeyInfo.Key) with executable code by using the delegate
// required 
using System.Collections.Generic;

// note the delegate must be defined outside any 'static context !
private delegate void KeyCommand();

// this can be defined in a static context
Dictionary<ConsoleKey, KeyCommand> KeysToCommands = new Dictionary<ConsoleKey, KeyCommand>
{
    {ConsoleKey.RightArrow, Right},
    {ConsoleKey.LeftArrow, Left},
    {ConsoleKey.DownArrow, Down},
    {ConsoleKey.UpArrow, Up}
};

使用这个字典,我们可以通过使用ConsoleKey值来访问可执行代码来执行任何方法: KeysToCommands [ConsoleKey.Up](); //执行'Up



注意:当您使用Console.ReadKey(true)时,返回值是ConsoleKeyInfo对象的一个​​实例(结构)。您从ConsoleKeyInfo.Key属性获取ConsoleKey值。



从C#3.0开始,可以使用Lambda表示法编写的匿名委托添加到C#语言/编译器;现在,您可以这样写:

Using this Dictionary, we can execute any method by using the ConsoleKey value to access the executable code: KeysToCommands[ConsoleKey.Up](); // executes 'Up

Note: when you use Console.ReadKey(true) the return value is an instance of the ConsoleKeyInfo object (struct). You get the ConsoleKey value from the ConsoleKeyInfo.Key property.

Beginning with C#3.0, anonymous delegates which can be written using Lambda notation were added to the C# language/compiler; so now, you can write this:

Dictionary<ConsoleKey, KeyCommand> KeysToCommands = new Dictionary<ConsoleKey, KeyCommand>
{
    {ConsoleKey.RightArrow, () => { x++; }},
    {ConsoleKey.LeftArrow, () => { x--; }},
    {ConsoleKey.DownArrow, () => { y++; }},
    {ConsoleKey.UpArrow, () => { y--; }},
};

了解委托及其灵活性是一个强大的工具,你会发现它有很多用途;委托是C#多播事件的基础:

Understanding delegates and their flexibility is a powerful tool that you will find has many uses; delegates are the basis for C# multi-cast Events:

"Events and delegates are tightly coupled concepts because flexible event handling requires that the response to the event be dispatched to the appropriate event handler. An event handler is typically implemented in C# via a delegate."

Jessie Liberty学习C#3.0,引用微软重新发布他的第17章[ ^ ]

Jessie Liberty "Learning C# 3.0" as quoted in Microsoft's re-publication of his Chapter 17 [^]


这篇关于我需要帮助搞清楚这个C#委托关键功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆