字符串转换成整型,到底使用int.Parse,Convert.ToInt32还是int.TryParse?

当我们想把一个字符串转换成整型int的时候,我们可能会想到如下三种方式:int.Parse,Convert.ToInt32和int.TryParse。到底使用哪种方式呢?

先来考虑string的可能性,大致有三种可能:
1、为null
2、不是整型,比如是字符串
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

        static void Main(string[] args)
        {
            string str = null;
            int result;
            if (int.TryParse(str, out result))
            {
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine("转换失败");
            }
            
            Console.ReadKey();
        }

结果:转换失败

总结:当需要捕获具体的转换异常的时候,使用int.Parse或Convert.ToInt32,而当string为null,Convert.ToInt32不会抛出ArgumentNullException异常;当只关注是否转换成功,推荐使用int.TryParse。当然,以上也同样适合其它值类型转换,比如decimal, 也有decimal.Parse,Convert.ToDecimal和decimal.TryParse。   

原文地址:https://www.cnblogs.com/darrenji/p/4358926.html