Possible Duplicate:
Whats the main difference between int.Parse() and Convert.ToInt32
Hi
I want to know what is the different between :
Convert.ToInt16 or Convert.ToInt32 or Convert.ToInt64
vs
Int.Pa开发者_运维技巧rse
both of them are doing the same thing so just want to know what the different?
Convert.ToInt
converts an object to an integer and returns 0 if the value was null.
int x = Convert.ToInt32("43"); // x = 43;
int x = Convert.ToInt32(null); // x = 0;
int x = Convert.ToInt32("abc"); // throws FormatException
Parse
convert a string to an integer and throws an exception if the value wasn't able to convert
int x = int.Parse("43"); // x = 43;
int x = int.Parse(null); // x throws an ArgumentNullException
int x = int.Parse("abc"); // throws an FormatException
Convert.ToInt32
will return 0 if the input string is null. Int32.Parse
will throw an exception.
Convert.To(s)
doesn't throw an exception when argument is null, butParse()
does.Convert.To(s)
returns 0 when argument is null.Int.Parse()
andInt.TryParse()
can only convert strings.Convert.To(s)
can take any class that implements IConvertible.Hence,Convert.To(s)
is probably a wee bit slower thanInt.Parse()
because it has to ask its argument what it's type is.
精彩评论