天天看點

Int32.Parse, Convert.ToInt32,Int32.TryParse三者的差別

nt32. parse (string)

int32.parse (string str) method converts the string representation of a number to its 32-bit signed integer equivalent. it takes a string and tries to extract an integer from it and returns the integer. when s is a null reference, it will throwargumentnullexception.

if str is not an integer value, it will throw formatexception. when str represents a number less than minvalue(−2,147,483,648) or greater than maxvalue(+2,147,483,647), it will throw overflowexception. for

example:

string str1 = "123";  string str2 = "123.45";  string str3 = "12312312356456456456456456456456";  string str4 = null;  int resultvalue;  resultvalue = int32.parse(str1); //-- 123  resultvalue = int32.parse(str2); //-- formatexception  resultvalue = int32.parse(str3); //-- overflowexception  resultvalue = int32.parse(str4); //-- argumentnullexception 

convert.toint32(string)

convert.toint32(string str) method converts the specified string representation of 32-bit signed integer equivalent. convert.toint32 underneath calls the int32.parse. the only difference is that if a null string is passed to convert it returns 0, whereas int32.parse

throws an argumentnullexception. if str is other than integer value, it will throw formatexception. when s represents a number less than minvalue(−2,147,483,648) or greater than maxvalue(+2,147,483,647),

it will throw overflowexception. for example: 

resultvalue = int32.parse(str4); //-- 0 

int32.tryparse(string, out int)

this method is available in c# 2.0 and above. int32.parse(string, out int) method converts the specified string representation of 32-bit signed integer equivalent to out variable, and returns true if it is parsed successfully else false. when input string  

is a null reference, it will return 0 rather than throw argumentnullexception as it was coming in above two methods. if input string  is other than an integer value, the out variable will have 0 rather than formatexception as

it was coming in above two methods. when input string  represents a number less than minvalue or greater than maxvalue, the out variable will have 0 rather than overflowexceptionas it was coming in above two methods. for example

bool isparsed; isparsed =int32.tryparse(str1, out resultvalue); //isparsed =>true; result => 123 isparsed =int32.tryparse(str2, out resultvalue); //isparsed => false; result => 0  isparsed =int32.tryparse(str3, out resultvalue); //isparsed => false; result => 0  isparsed =int32.tryparse(str4, out resultvalue); // isparsed => false; result => 0 

so from above you came to know about s several different ways to extract integers from strings in

.net. you should therefore use the method that better suits your scenario. if you've got a string, and you expect it to always be an integer use int32.parse.if you are expecting input other than integer use convert.toint32 and

if you don’t want any exception you can go for int32.tryparse