关于int.TryParse的使用-LMLPHP

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string TP = "123abc";
string TPE = "";
int re,ret;
//测试转换失败
if (int.TryParse(TP, out re) == true)
{
Console.WriteLine("{0}能转换成功,转换后的数为:{1}",TP,re );
}
else
{
Console.WriteLine("{0}转换失败",TP);
}
//暂停
Console.ReadKey();
Console.WriteLine();
//测试转换成功
if (int.TryParse(TPE, out ret) == true)
{
Console.WriteLine("{0}能转换成功,转换后的数为:{1}" ,TPE,ret);
}
else
{
Console.WriteLine("{0}转换失败",TPE);
}
//暂停
Console.ReadKey();
}
}
}

实现int.TryParse的原理:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
int re;
string s = "";
if (IntTryParse(s, out re))
{
Console.WriteLine("转换成功!" + re);
Console.ReadKey();
}
else
{
Console.WriteLine("转换失败!");
Console.ReadKey();
}
} static bool IntTryParse(string s, out int result)//模仿TryParse定义方法IntTryParse
{
result = ;
try
{
result = Convert.ToInt32(s);
return true;
}
catch
{
return false;
}
}
}
}
05-02 22:45