If you don't go after what you want, you'll never have it. If you don't step forward, you're always in the same place.

C# Parse and TryParse 方法详解

工作中遇到的常用方法:

Parse and TryParse 

TryParse  方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常

 

复制代码
 1  /// <summary>
 2         /// TryParse  方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常
 3         /// </summary>
 4         public static void TryParseExample()
 5         {
 6             String[] values = { null, "160519", "9432.0", "16,667", "   -322   ", "+4302", "(100);", "01FA", "ab123" };
 7             foreach (var value in values)
 8             {
 9                 int number;
10 
11                 bool result = Int32.TryParse(value, out number);
12                 if (result)
13                 {
14                     Console.WriteLine("Converted '{0}' to {1}.", value, number);
15                 }
16                 else
17                 {
18                     //            if (value == null) value = ""; 
19                     Console.WriteLine("Attempted conversion of '{0}' failed.",
20                                        value == null ? "<null>" : value);
21                 }
22             }
23         }
24 
25         /// <summary>
26         /// 
27         /// </summary>
28         public static void ParseExample()
29         {
30             String[] values = { null, "160519", "9432.0", "16,667", "   -322   ", "+4302", "(100);", "01FA", "ab123" };
31             foreach (var value in values)
32             {
33                 try
34                 {
35                     int result = Int32.Parse(value);
36                     Console.WriteLine("Converted '{0}' to {1}.", value, result);
37                 }
38                 catch (Exception ex)
39                 {
40                     Console.WriteLine("Unable to convert '{0}'.", value);
41                     Console.WriteLine(string.Format("{0}-{1}", ex.Message, ex.GetType()));
42                 }
43             }
44         }
复制代码

 

posted @   BlackAnts  阅读(15925)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示