如何在阅读行时继续检查用户是否按了 esc 键?
How to keep checking if a user presses esc while Reading lines?
我想继续阅读用户的行,但是当这个用户按下退出键时我想让它停止。但是我怎样才能在阅读行的同时继续阅读单个键(用于逃生)?我希望在给出我的代码后问题会更清楚:
int number;
do
{
string a = Console.ReadLine();
try
{
Int32.TryParse(a, out number);
}
catch
{
Console.WriteLine("I only accept int");
}
finally
{
Console.Writeline(number);
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
我不确定是否完全理解你的问题,但你可以测试下面的代码是否符合你的要求
using System;
using System.Globalization;
namespace Whosebug_31111668
{
class Program
{
static void Main()
{
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
var a = Console.ReadLine();
int number;
Console.WriteLine(!int.TryParse(a, out number) ? "I only accept int" : number.ToString(CultureInfo.InvariantCulture));
}
}
}
}
如您所写,您想要读取行直到按下转义符,但正如您的代码所说,您只想读取整数。这就是我认为的你想要的,
int number = 0;
do
{
while (!Console.KeyAvailable)
{
string a = Console.ReadLine();
bool bWriteNumber = false;
try
{
number = int.Parse(a);
bWriteNumber = true;
}
catch
{
Console.WriteLine("Sorry! I only accept int");
}
finally
{
if (bWriteNumber)
Console.WriteLine(number);
}
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
我想继续阅读用户的行,但是当这个用户按下退出键时我想让它停止。但是我怎样才能在阅读行的同时继续阅读单个键(用于逃生)?我希望在给出我的代码后问题会更清楚:
int number;
do
{
string a = Console.ReadLine();
try
{
Int32.TryParse(a, out number);
}
catch
{
Console.WriteLine("I only accept int");
}
finally
{
Console.Writeline(number);
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
我不确定是否完全理解你的问题,但你可以测试下面的代码是否符合你的要求
using System;
using System.Globalization;
namespace Whosebug_31111668
{
class Program
{
static void Main()
{
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
var a = Console.ReadLine();
int number;
Console.WriteLine(!int.TryParse(a, out number) ? "I only accept int" : number.ToString(CultureInfo.InvariantCulture));
}
}
}
}
如您所写,您想要读取行直到按下转义符,但正如您的代码所说,您只想读取整数。这就是我认为的你想要的,
int number = 0;
do
{
while (!Console.KeyAvailable)
{
string a = Console.ReadLine();
bool bWriteNumber = false;
try
{
number = int.Parse(a);
bWriteNumber = true;
}
catch
{
Console.WriteLine("Sorry! I only accept int");
}
finally
{
if (bWriteNumber)
Console.WriteLine(number);
}
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);