posts - 930,  comments - 588,  views - 402万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

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

   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
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on   PetterLiu  阅读(1687)  评论(2编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示