字符串转换成整型,到底使用int.Parse,Convert.ToInt32还是int.TryParse?当我们想把一个字符串转换成整型int的时候,我们可能会想到如下三种方式:int.Parse,Convert.ToInt32和int.TryParse。到底使用哪种方式呢?
先来考虑string的可能性,大致有三种可能:1、为null2、不是整型,比如是字符串3、超出整型的范围
基于string的三种可能性,分别尝试。
□ 使用int.Parse
string str = null;
int result;
result = int.Parse(str);
以上,抛出ArgumentNullException异常。
string str = "hello";
int result;
result = int.Parse(str);
以上,抛出FormatException异常。
string str = "90909809099090909900900909090909";
int result;
result = int.Parse(str);
以上,抛出OverflowException异常。
□ 使用Convert.ToInt32
static void Main(string[] args)
{
string str = null;
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
以上,显示0,即当转换失败,显示int类型的默认值,不会抛出ArgumentNullException异常。
static void Main(string[] args)
{
string str = "hello";
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
以上,抛出FormatException异常。
static void Main(string[] args)
{
string str = "90909809099090909900900909090909";
int result;
result = Convert.ToInt32(str);
Console.WriteLine(result);
Console.ReadKey();
}
以上,抛出OverflowException异常。
□ 使用int.TryParse
PRe style="overflow: auto; border-top: #cecece 1px solid; border-right: #cecece 1