/// <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())); } } }
时间: 2024-12-29 12:59:33