Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
String myString = "1234 ";
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 ");
}
}
}
On the surface, it can be seen that the three methods have achieved the same effect!
Let's change the 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 ");
Running result:
If Convert. ToInt32 () is null, 0 is returned instead of an exception;
Int32.Parse () should throw an exception;
If Int32.TryParse () does not throw an exception, true or false is returned to indicate whether the resolution is successful. If a parsing error occurs, the caller will get a value of 0.
Conclusion:
There are almost no differences between the three methods!
If you want to pursue perfection, consider the performance differences:
Int32.TryParse () is better than Int32.Parse () than Convert. ToInt32 ().
Personal suggestion: Use Int32.Parse () in. NET1.1; Use Int32.TryParse () in. NET2.0 ().
Why?
Because: Convert. toInt32 will delegate the final parsing work to Int32.Parse, while Int32.Parse and Int32.TryParse respectively proxy the parsing work directly to Number. parseInt32 and Number. tryParseInt32: the former throws an exception when a parsing error occurs, while the latter returns only false.