我这里有一段重复代码,充满了 goto
语句,使这个 while 循环很好......永远重复。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
main();
}
public static ConsoleKeyInfo keyPressed;
private static void main()
{
start:
keyPressed = Console.ReadKey();
while (true)
{
loopstart:
if (keyPressed.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed the Enter Key!");
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed the Escape Key!");
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Spacebar)
{
Console.WriteLine("You pressed the Spacebar!");
goto loopstart;
}
else
{
break;
}
}
Console.WriteLine("You broke the loop!");
goto start;
}
}
}
在不删除任何代码的情况下,是否可以将keyPressed.Key
或keyPressed
本身的值更改为NULL
;声明时的状态,或不是空格键、输入键或转义键的任何其他值/键?
当然,把代码中的goto loopstart;
全部去掉就可以解决问题,但这与问题的重点不符。
我想做的是使 keyPressed.Key
值 NULL
(或任何其他值),以便所有 IF
语句都将结果为 false,因此意味着不运行 goto loopstart
代码。
现在的问题是,当我尝试用一个简单的 keyPressed = null;
使它无效时,它会出现以下错误:
Cannot convert null to 'System.ConsoleKeyInfo' because it is a non-nullable value type.
有什么方法可以取消(或将值更改为其他值)以便打破循环?
(如:使 IF
语句到达必须运行 else
代码的位置)
它应该看起来像:
...
{
loopstart:
if (keyPressed.Key == ConsoleKey.Enter)
{
Console.WriteLine("You pressed the Enter Key!");
// keyPressed = null; <-- Does not work.
// Do something to make ConsoleKey.Key to equal something else.
goto loopstart;
}
if (keyPressed.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed the Escape Key!");
...
显然 //做一些事情使 ConsoleKey.Key 等于其他东西。
替换为工作代码?
如果这可行,循环第一次运行时(假设开始时按下的键是空格键、退出键或回车键)将导致 goto loopstart;
被使用,并且第二轮会跳到 goto start;
那里会要求另一个 key 。
然后该过程以用户输入的速度重复,而不是不停地重复使用同一个键,或要求另一个键。
基本上:使循环运行 IF
语句作为适当的 IF
语句而不是 FOR
循环。
最佳答案
为什么要使用 goto
语句,这是非常过时的结构。您可以轻松地继续
循环。而else
检查也是多余的。您可以在检查之前简单地从 Console
读取 key ,如下所示:
while (true)
{
keyPressed = Console.ReadKey();
switch (keyPressed.Key)
{
case ConsoleKey.Enter:
Console.WriteLine("You pressed the Enter Key!");
continue;
case ConsoleKey.Escape:
Console.WriteLine("You pressed the Escape Key!");
continue;
case ConsoleKey.Spacebar:
Console.WriteLine("You pressed the Spacebar!");
continue;
}
// should be outside the switch for breaking the loop
break;
}
如果你想清除keyPressed
,使用default
结构,像这样:
keyPressed = default(ConsoleKeyInfo);
但是为什么要这样做呢? Garbage Collection 会自己清除内存,你不应该去那里。
关于c# - 在 System.ConsoleKey 值使用完毕后,如何使它无效(或分配另一个值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447823/