-1

我在格式和转换方面遇到问题。

我已经尝试了所有解决方法,但没有。

我认为错误所在的代码片段

label_Map.Text = message.Substring(21, 3);
label_Sys.Text = message.Substring(15, 3);
label_Dia.Text = message.Substring(18, 3);
label_Pulse.Text = message.Substring(26, 3);

SaveData(
    Int32.Parse(message.Substring(15, 3)),
    Int32.Parse(message.Substring(18, 3)),
    Int32.Parse(message.Substring(26, 3)));

示例输入字符串

S1;A0;C03;M00;P120080100;R075;T0005;;D2

错误代码结束

InnerException: System.FormatException    
Message=Input string was not in a correct format.   
Source=mscorlib   
StackTrace:  
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number,  NumberFormatInfo info, Boolean parseDecimal)  
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)  
at NIBP2PC.Form1.display(String message) in C:\Users\bazinga\Desktop\spiediena_merisana\NIBP2PC_c#\NIBP2PC\Form1.cs:line 427
4

3 回答 3

1

使用带有 ';' 的拆分方法 作为分隔符.. 然后为每个字符串在字符中执行一个循环以检查是否为数字(Char.IsDigit())。如果是数字返回 false 则退出循环(你知道它不是数字)。使用 try{}catch{} 语句可以归档更少的代码。在里面尝试使用转换器将字符串转换为int。如果它失败了,那么在 tha catch 你知道该怎么做......

于 2013-05-14T16:08:42.753 回答
1

您可能会更成功地尝试解析出您想要的字符串。

public class InputCapture
{
    public string Attribute { get; set; }
    public int Value { get; set; }
}

public class InputParser
{
    const string pattern = @"(\w)(\d+)";
    private static readonly Regex Regex = new Regex(pattern);

    public IEnumerable<InputCapture> Parse(string input)
    {
        var inputs = input.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        var parsedInputs = inputs.Where(i => Regex.IsMatch(i))
                             .Select(i => Regex.Match(i))
                             .Select(r =>
                                new InputCapture
                                    {
                                        Attribute = r.Groups[1].Value,
                                        Value = int.Parse(r.Groups[2].Value)
                                    });

        return parsedInputs;
    }
}

解析结果

于 2013-05-14T16:26:21.290 回答
0

您的子字符串可能返回“P12”或“00;”之类的内容 无法解析。因此,错误消息是正确的(或者更确切地说,它告诉您问题到底是什么)。在修复要发送的字符串之前,您不会获得任何数据,但更好的方法是使用“TryParse”

int myInt;
if (!Int32.TryParse(myString, out myInt)) throw new Exception() //or something more reasonable
于 2013-05-14T16:01:29.280 回答