首页 > 学院 > 开发设计 > 正文

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

2019-11-17 02:30:21
字体:
来源:转载
供稿:网友

字符串转换成整型,到底使用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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表