我遇到格式和转换问题。
我已尝试过所有变通办法,但没有。
我认为错误
的代码段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
答案 0 :(得分:1)
将Split方法与';'一起使用as delimiter ..然后为每个字符串在字符中执行一个循环以检查是否为数字(Char.IsDigit())。如果是数字返回false则退出循环(你知道它不是数字)。可以使用try {} catch {}语句存档更少的代码。在里面尝试使用转换器将字符串转换为int。如果它失败了那么你知道该怎么做......
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
您的子字符串可能会返回“P12”或“00;”之类的内容无法解析。因此错误消息是正确的(或者更确切地说,它告诉你问题到底是什么)。在修复发送的字符串之前,您不会获得任何数据,但更好的方法是使用“TryParse”
int myInt;
if (!Int32.TryParse(myString, out myInt)) throw new Exception() //or something more reasonable