當我們想把一個字符串轉(zhuǎn)換成整型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
以上,顯示0,即當轉(zhuǎn)換失敗,顯示int類型的默認值,不會拋出ArgumentNullException異常。static void Main(string[] args){string str = null;int result;result = Convert.ToInt32(str);Console.WriteLine(result);Console.ReadKey();}
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新聞熱點
疑難解答