码迷,mamicode.com
首页 > 其他好文 > 详细

Parse and TryParse

时间:2017-08-05 21:53:48      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:style   str   ati   mat   span   and   pre   bool   value   

        /// <summary>
        /// TryParse  方法类似于 Parse 方法,不同之处在于 TryParse 方法在转换失败时不引发异常
        /// </summary>
        public static void TryParseExample()
        {
            String[] values = { null, "160519", "9432.0", "16,667", "   -322   ", "+4302", "(100);", "01FA", "ab123" };
            foreach (var value in values)
            {
                int number;

                bool result = Int32.TryParse(value, out number);
                if (result)
                {
                    Console.WriteLine("Converted ‘{0}‘ to {1}.", value, number);
                }
                else
                {
                    //            if (value == null) value = ""; 
                    Console.WriteLine("Attempted conversion of ‘{0}‘ failed.",
                                       value == null ? "<null>" : value);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public static void ParseExample()
        {
            String[] values = { null, "160519", "9432.0", "16,667", "   -322   ", "+4302", "(100);", "01FA", "ab123" };
            foreach (var value in values)
            {
                try
                {
                    int result = Int32.Parse(value);
                    Console.WriteLine("Converted ‘{0}‘ to {1}.", value, result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to convert ‘{0}‘.", value);
                    Console.WriteLine(string.Format("{0}-{1}", ex.Message, ex.GetType()));
                }
            }
        }

 

Parse and TryParse

标签:style   str   ati   mat   span   and   pre   bool   value   

原文地址:http://www.cnblogs.com/lolitagis/p/7291395.html

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