Q: How do I parse a string to int?
A: There are three kinds of simple methods:
string source = "1412";
int result = 0;
// 使用Convert.ToInt32(string value);
result = Convert.ToInt32(source);
// 使用Int32.Parse(string value);
result = Int32.Parse(source);
// 使用Int32.TryParse(string s, out int result);
Int32.TryParse(source, out result);
Q: What is the difference between these three methods?
A: A simple answer is:
If parsing fails, int32.parse (source) always throws an exception, and Convert.ToInt32 (source) does not throw an exception when source is null, but simply returns 0 to the caller; Int32.TryParse ( Source, result) does not throw an exception anyway, only returns true or false to indicate whether the parse succeeded, and if parsing fails, the caller will get a value of 0.
Q: If the literal value of the string I am parsing is not decimal, then the return value obtained from these methods is problematic. Is there any way to solve it?
A: Then you will need the corresponding overloaded version of these methods, a simple way is to use the Convert class
public static int ToInt32(string value, int fromBase);
The value of the frombase can only be 2, 8, 10, or 16, which specifies the method of the system. If the frombase is not a specified value or the value is not decimal and has a prefix plus sign, the ArgumentException is thrown.
String Source = "0x1412"; The 0x (or 0X) prefix here is optional.
int result = Convert.ToInt32 (source, 16);
Of course, you can also pass for the Int32 class
public static int Parse(string s, NumberStyles style);
Specify Numberstyles.allowhexspecifier or Numberstyles.hexnumber to parse the hexadecimal literal string for the second argument, at which point you need to reference the System.Globalization namespace.
Or use the Int32 class
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result);
and specify Numberstyles.allowhexspecifier or Numberstyles.hexnumber as the second argument, and NULL as the third parameter to parse the hexadecimal literal string. You should, of course, refer to the System.Globalization namespace.
One thing to note here is that regardless of the parse or TryParse method used to parse hexadecimal, the string cannot have a 0x or 0X prefix, or an exception will be thrown.