您的位置:首页 > 编程语言 > C#

C#将字符串转换为整型

2011-10-13 14:59 218 查看
int numVal = Convert.ToInt32("29");
numVal++;

Console.WriteLine(numVal);
// Output: 30
=================================================

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105

==================================================

int j;
Int32.TryParse("-105", out j);
Console.WriteLine(j);
// Output: -105

==================================================

try
{
int m = Int32.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.

===================================================

string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: