在开始循环之前捕获错误
本文关键字:错误 开始 循环 | 更新日期: 2023-09-27 18:26:27
编辑:提供了更多代码。
我有一个for循环,看起来像这样:
public void SendCommand(string userInput)
{
string[] _command = userInput.Split('#', '>');
string[] _keypress = _command.Where((value, index) => index % 2 == 0).ToArray(); //Even array = Keypress
string[] _count = _command.Where((value, index) => index % 2 != 0).ToArray(); // Odd array = keypress count
int keypressLength = _keypress.GetLength(0);
for (int j = 0; j < keypressLength; j++) //loop through all indices
{
for (int i = 0; i < int.Parse(_count[j]); i++) //repeat convert command for #X times
{
ConvertCommand(_keypress[j]);
Thread.Sleep(100); // wait time after each keypress
}
}
}
在上面的代码周围使用"try-catch",如果用户输入无效,则会在循环的中途抛出异常。然而,我想在循环开始之前就发现错误,我该如何实现呢?
您可以使用int.TryParse
。它尝试解析字符串并返回true
或false
:
for (int j = 0; j < keypressLength; j++) //loop through all indices
{
int limit;
if (!int.TryParse(_count[j], out limit))
{
// Show an error like "_count[j] cannot be parsed"
continue;
}
for (int i = 0; i < limit; i++)
{
ConvertCommand(_keypress[j]);
Thread.Sleep(100); // wait time after each keypress
}
}
如果用户不断输入不正确的数据,您可能还希望在ConvertCommand
中实现某种验证。
更新:
例如,可以解析_count[0],但不能解析_count[1],当它发现错误时,_count[0]已经被处理。如果出现任何错误,我不希望对其中任何一个进行处理。
您可以使用相同的int.TryParse
并使用LINQ来检查_count
中的所有字符串是否可以解析为整数:
int stub;
if (_count.Any(x => !int.TryParse(x, out stub)))
{
// There is a non-integer string somewhere!
}
for (int j = 0; j < keypressLength; j++) //loop through all indices
{
for (int i = 0; i < int.Parse(_count[j]); i++)
{
ConvertCommand(_keypress[j]);
Thread.Sleep(100); // wait time after each keypress
}
}