[C#]用TryParse取代Parse

  • 11552
  • 0
  • C#
  • 2012-10-09

[C#]用TryParse取代Parse

用Parse會引發例外,用TryParse幫我們把值轉型 成功回傳true,轉型失敗會轉成初始值,並回傳false 不會引發例外


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string cdate = "aaaa/a/a/";
            try
            {
                DateTime dt =   DateTime.Parse(cdate);
             }
            catch (Exception ex)
            {
                Console.WriteLine(cdate+ ex.Message.ToString()); 
            }
           
            DateTime trydate; 
            if (DateTime.TryParse(cdate, out trydate))
            {//回傳true
                Console.WriteLine(trydate);
            }
            else {
                Console.WriteLine(trydate + "不正確的日期格式");
            }
 
            Console.ReadKey();
        } 
    }
}

 


如有錯誤 歡迎指正