码迷,mamicode.com
首页 > Windows程序 > 详细

C# Parse and TryParse 方法详解

时间:2014-11-19 13:53:04      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

工作中遇到的常用方法:

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         }

 

C# Parse and TryParse 方法详解

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/htwdz-qhm/p/4107933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!