这两个方法我们经常在使用,但是它们之间有什么区别呢,下面的代码让你比较清晰的明白区别所在:
1: string convertToInt = "12";
2: string nullString = null;
3: string maxValue = "32222222222222222222222222222222222";
4: string formatException = "12.32";
5:
6: int parseResult;
7:
8: // It will perfectly convert interger
9: parseResult = int.Parse(convertToInt);
10:
11: // It will raise Argument Null Exception
12: parseResult = int.Parse(nullString);
13:
14: //It willl raise Over Flow Exception
15: parseResult = int.Parse(maxValue);
16:
17: //It will raise Format Exception
18: parseResult = int.Parse(formatException);
19:
20:
21: //For Convert.ToInt32
22:
23: //It will perfectly convert integer
24: parseResult = Convert.ToInt32(convertToInt);
25:
26: //It will ouput as 0 if Null string is there
27: parseResult = Convert.ToInt32(nullString);
28:
29: //It will raise Over Flow Exception
30: parseResult = Convert.ToInt32(maxValue);
31:
32: //It will raise Format Exception
33: parseResult = Convert.ToInt32(formatException);
区别就是Convert.ToInt32(string) 方法遇到空时会返回0,而Int.Parse则会Throw Exception. 我们还可以使用Int32.TryParse方法更加安全。
希望这篇POST对您开发有帮助。
Petter Liu Blog。