C# 在开始循环之前捕获错误
编辑:提供了更多的代码 我有一个for循环,看起来像这样:C# 在开始循环之前捕获错误,c#,for-loop,try-catch,C#,For Loop,Try Catch,编辑:提供了更多的代码 我有一个for循环,看起来像这样: public void SendCommand(string userInput) { string[] _command = userInput.Split('#', '>'); string[] _keypress = _command.Where((value, index) => index % 2 == 0).ToArray(); //Even array = Keypress string
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
}
}
}
public void SendCommand(字符串userInput)
{
string[]\u command=userInput.Split('#','>');
字符串[]\u keypress=\u命令。其中((值,索引)=>索引%2==0)。ToArray();//偶数数组=keypress
字符串[]\u count=\u命令。其中((值,索引)=>索引%2!=0)。ToArray();//奇数数组=按键计数
int keypressLength=\u keypress.GetLength(0);
for(int j=0;j
在上述代码周围使用“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
的性质,我们就不可能知道a)如何预先检查所有操作是否正常,b)是否可以预先检查(即,如果与外部系统有任何交互,那么在您实际尝试该命令时,再多的预检查都不会告诉您该命令是否正常工作)哪个部分是无效输入-\u count[j]
或\u keypress[j]
?我个人会对外循环的每次迭代执行一次解析,而不是对内循环的每次迭代执行一次解析…验证前面的输入并继续验证是否有效的问题在哪里?如果循环中的任何命令引发异常,应用程序在执行之前应该如何停止?例如,\u count[0]
可以被解析,但是\u count[1]
不能,当它捕获错误时,\u count[0]
已经被处理。如果出现任何错误,我不希望对其中任何一个进行处理。@Liren检查更新的答案。谢谢!我不停地钻研try catch
,完全进入了错误的思维方向。
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
}
}