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         }

 

C# Parse and TryParse 方法详解

上一篇:C# First and FirstOrDefault 方法详解


下一篇:F1Book报表在Win7下运行出现显示不完整问题