这两个方法我们经常在使用,但是它们之间有什么区别呢,下面的代码让你比较清晰的明白区别所在:

   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。

相关文章:

  • 2022-02-27
  • 2022-12-23
  • 2022-03-02
  • 2021-08-19
  • 2022-12-23
  • 2021-05-27
猜你喜欢
  • 2021-10-09
  • 2021-09-08
  • 2022-01-17
相关资源
相似解决方案