0

我的应用程序每 6 秒从串行端口接收一个格式为“・99,99999,99999,99999,AAAAAA,AAAAAA”的字符串。我使用这些语句来处理字符串:

            stringOut=stringOut.Replace("-",",");
            string[] valor_1=stringOut.Split(',');
            int i_C_AR=Convert.ToInt32(lbl_contador.Text);

            mx_02=Convert.ToInt32(valor_1[1])-Convert.ToInt32(valor_1[2]);
            mx_07=Convert.ToInt32(valor_1[2])-Convert.ToInt32(valor_1[3]);
            mx_10=Convert.ToInt32(valor_1[3]);

在大多数情况下,我们可以毫无问题地得到字符串。

有时应用程序会因为这些语句后的某些字符出现在错误的位置而中止。

mx_02=Convert.ToInt32(valor_1[1])-Convert.ToInt32(valor_1[2]);
mx_07=Convert.ToInt32(valor_1[2])-Convert.ToInt32(valor_1[3]);
mx_10=Convert.ToInt32(valor_1[3]);

如何保护应用不中断?

4

2 回答 2

4

首先,您应该弄清楚为什么会收到不良数据。这真的是预期的,还是它代表系统中其他地方的错误,这可能会导致应用程序终止而不是继续处理错误数据?

您可以使用int.TryParse而不是Convert.ToInt32. 这将允许您检测错误而无需捕获异常(这是一种替代方法)。

TryParse返回一个bool结果,说明解析是否成功,并使用一个out参数来存储结果。在稍后执行算术之前,您需要引入额外的局部变量来存储解析结果。例如,您可能需要以下内容:

// Rename these to be meaningful - in general your variable names should be
// clearer, and ideally without the underscores
int first, second, third;
if (!int.TryParse(valor_1[1], out first) ||
    !int.TryParse(valor_1[2], out second) ||
    !int.TryParse(valor_1[3], out third))
{
    // Do whatever you need to with invalid input
}
else
{
    mx_02 = first - second;
    mx_07 = second - third;
    mx_10 = third;
}

请注意,这也会减少您将要执行的解析操作的数量。

于 2012-09-25T09:00:31.610 回答
0

可以使用int.TryParse,或者catch异常,会更简单

try{
// place faulty code here
}catch(Exception ex)
{
// handle exception if you care
}
于 2012-09-25T09:03:01.953 回答