字符串轉換成整型,到底使用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。   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM