C# Parse and TryParse 方法詳解

來源:互聯網
上載者:User

標籤: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                 else17                 {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                 try34                 {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 方法詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.