Parse and TryParse

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Parse and TryParse相关的知识,希望对你有一定的参考价值。

        /// <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的主要内容,如果未能解决你的问题,请参考以下文章

Parse 诉 TryParse

C# Parse 和 TryParse

int.Parse()与int.TryParse()

更好的是: int.TryParse 或 try int.Parse() catch [关闭]

int.Parse()int.TryParse()和Convert.ToInt32()的区别

tryParse的用法。