最近我的C#代码遇到了一个问题,起初我的目标是制作一个简单的程序,当用户按下键盘上的某个键时显示键盘按键代码,但在用户按下之前它仅限于一次操作退出并重新打开程序进行其他操作。
所以我决定对其进行编辑,并使其在一组中执行多个操作(如果不关闭,可能会永远执行?)
代码的第一个版本:
{
internal class Program
{
static void Main(string[] args)
{
string pressKey = "Write any character/symbol to find it's key code: \n\n";
string asciiArt = "null";\\left it because it looks ugly here
string quit = "Press 'Home' to exit and try again...";
Console.Title = "ValueFinder";
Console.Write(pressKey);
Console.WriteLine(asciiArt);
int Value = Console.Read();
Console.WriteLine($"Keyboard Key Code Value:{Value}\n");
Console.WriteLine(quit);
while (true)
{
if (Console.ReadKey(true).Key == ConsoleKey.Home)
{
break;
}
}
}
}
}
这个只做一项操作,
所以我将代码编辑为:
static void Main(string[] args)
{
string pressKey = "Write any character/symbol to find it's key code: \n\n";
string asciiArt = "null";
string quit = "Press 'Home' to try again...";
Console.Title = "ValueFinder";
Console.Write(pressKey);
Console.WriteLine(asciiArt);
int Value = Console.Read();
Console.WriteLine($"Keyboard Key Code Value:{Value}\n");
Console.WriteLine(quit);
while (true)
{
if (Console.ReadKey(true).Key == ConsoleKey.Home)
{
Console.Clear();
Console.Write(pressKey);
Console.WriteLine(asciiArt);
int Value1 = Console.Read();
Console.WriteLine($"Keyboard Key Code Value: {Value}\n");
Console.WriteLine(quit);
while (true)
{
if (Console.ReadKey(true).Key == ConsoleKey.Home)
break;
}
}
}
}
这里的问题是,按“Home”键后,程序完全失去了功能,当您第一次打开程序时,程序应该将控制台重置为默认屏幕,它实际上确实如此,但完全没有任何功能,我发现按“Home”键后“Home 键”大约 5 次或更多,它将恢复功能,但在执行一次操作后,同样的事情会一遍又一遍地发生。
第二个问题我不知道它是否会影响某些东西,
int Value1 = Console.Read();
,不能命名为“Value”,因为它会给我一个错误:
错误 CS0136 无法在此范围内声明名为“Value”的本地或参数,因为该名称在封闭的本地范围中使用来定义本地或参数。
第三个问题,我完全没有经验,几天前才开始,所以我似乎无法弄清楚可能发生的这个问题,因为我只是以错误的方式做,所以请耐心等待。
将局部变量“Value”重命名为“Value1”,它修复了错误,但现在它是“对 value1 不必要的赋值”
Value = Console.Read();
似乎解决了用户 @ralf 提到的功能问题。
第一个问题是因为控制台打印了“Enter”ASCII码(10)和回车符(13)。