首页 > 代码库 > Parse and TryParse
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 =http://www.mamicode.com/= 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。