将String转换为Integer

zac*_*ack 9 c# string

可能重复:
如何将String转换为Int?

嗨,

我有以下问题将字符串转换为整数:

string str = line.Substring(0,1);

//This picks an integer at offset 0 from string 'line' 
Run Code Online (Sandbox Code Playgroud)

所以现在string str包含一个整数.我正在做以下事情:

int i = Convert.ToInt32(str);
Run Code Online (Sandbox Code Playgroud)

如果我写下面的语句,我应该打印一个整数吗?

Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)

它编译时没有任何错误,但在运行时出现以下错误:

mscorlib.dll中发生了未处理的"System.FormatException"类型异常

附加信息:输入字符串的格式不正确.

有什么帮助吗?

Sco*_*man 19

而不是使用Convert.ToInt32(string)你应该考虑使用Int32.TryParse(string, out int)而不是.TryParse方法可以帮助以更安全的方式处理用户提供的输入.导致错误的最可能原因是您返回的子字符串具有整数值的无效字符串表示形式.

string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
   Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)