1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication7 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string TP = "123abc"; 14 string TPE = "123"; 15 int re,ret; 16 //测试转换失败 17 if (int.TryParse(TP, out re) == true) 18 { 19 Console.WriteLine("{0}能转换成功,转换后的数为:{1}",TP,re ); 20 } 21 else 22 { 23 Console.WriteLine("{0}转换失败",TP); 24 } 25 //暂停 26 Console.ReadKey(); 27 Console.WriteLine(); 28 //测试转换成功 29 if (int.TryParse(TPE, out ret) == true) 30 { 31 Console.WriteLine("{0}能转换成功,转换后的数为:{1}" ,TPE,ret); 32 } 33 else 34 { 35 Console.WriteLine("{0}转换失败",TPE); 36 } 37 //暂停 38 Console.ReadKey(); 39 } 40 } 41 }
实现int.TryParse的原理:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication7 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int re; 14 string s = "1233"; 15 if (IntTryParse(s, out re)) 16 { 17 Console.WriteLine("转换成功!" + re); 18 Console.ReadKey(); 19 } 20 else 21 { 22 Console.WriteLine("转换失败!"); 23 Console.ReadKey(); 24 } 25 } 26 27 static bool IntTryParse(string s, out int result)//模仿TryParse定义方法IntTryParse 28 { 29 result = 0; 30 try 31 { 32 result = Convert.ToInt32(s); 33 return true; 34 } 35 catch 36 { 37 return false; 38 } 39 } 40 } 41 }