那麼我們把代碼改一下:
C# CODE
//string myString = "1234";
string myString = null;
int myint = 0;
myint = Convert.ToInt32(myString);
Console.Write(myint+"\r\n");
myint = Int32.Parse(myString);
Console.Write(myint+"\r\n");
Int32.TryParse(myString, out myint);
Console.Write(myint+"\r\n");
這次字符串是null,那麼運行結果會怎樣呢?
(程序將會異常!)
這是因為如果解析錯誤:
Convert.ToInt32()在null時不拋異常而是返回0;
Int32.Parse()要拋異常;
Int32.TryParse()不拋異常,會返回true或false來說明解析是否成功,如果解析錯誤,調用方將會得到0值。
由於Convert.ToInt32()在null時我們看不到Int32.TryParse()的運行結果所以再分調試和不調試來看結果的差異:
調試:
(將會看到 TryParse 返回 false。圖略)
其實一般出bug畢竟屬於少數,而且大家都會測試保證不出bug,那麼我們最關心的或許就是性能。
再把代碼修改一下:
C# CODE
string myString1 = "1234";
//string myString = null;//清清月兒 http://blog.csdn.Net/21ASPnet/
int myint = 0;
Console.Write(System.DateTime.Now.ToString()+" "+System.DateTime.Now.Millisecond.ToString() + " ");
for (int i = 0; i < 1000000;i++ )
...{
myint = Convert.ToInt32(myString1);
}
Console.Write(myint + " \r\n");
Console.Write(System.DateTime.Now.ToString() + " " + System.DateTime.Now.Millisecond.ToString() + "\r\n ");
string myString2 = "1234";
for (int i = 0; i < 1000000; i++)
...{
myint = Int32.Parse(myString2);
}
Console.Write(myint + "\r\n ");
Console.Write(System.DateTime.Now.ToString() + " " + System.DateTime.Now.Millisecond.ToString() + " ");
string myString3 = "1234";
for (int i = 0; i < 1000000; i++)
...{
Int32.TryParse(myString3, out myint);
}
Console.Write(myint + "\r\n ");
Console.Write(System.DateTime.Now.ToString() + " " + System.DateTime.Now.Millisecond.ToString() + "\r\n ");
(執行效果圖略,所耗時間基本相差不遠)