TryParse()方法可以把字符串转化为对应的数据类型,但是和Parse()不同的是,它执行过程中转化出错,并不会抛出异常,他的返回值是bool类型
class Program { static void Main(string[] args) { Student stu = new Student(); stu.Age = 11.2; stu.Receive(stu.Age); } class Student { public double Age; public void Receive(double age) { Console.WriteLine("请输入double类型的数据"); string ars= Console.ReadLine(); bool dou1 = double.TryParse(ars,out age); if (dou1 == false) { Console.WriteLine("输入的参数有误,请重新输入"); Receive(age); } else { Console.WriteLine("恭喜输入正确"); } } } }
然而Parse()方法却要抛出异常
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.Age = 11.2;
stu.Receive(stu.Age);
}
class Student
{
public double Age;
public void Receive(double age)
{
Console.WriteLine("请输入double类型的数据");
string ars= Console.ReadLine();
try
{
double dou1= double.Parse(ars);
Console.WriteLine("恭喜输入正确");
}
catch (Exception ex)
{
Console.WriteLine("{0}", ex.Message);
Receive(age);
}
}
}
}
原文:https://www.cnblogs.com/zxbls/p/13137851.html