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         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM