using System;
namespace _020_类型转换
{
class Program
{
static void Main(string[] args)
{
#region Convert的用法
//Convert.ToInt32(~~~)
Console.WriteLine("Convert.ToInt32类型转换:");
Console.WriteLine("如果你输入int类型,就会正常赋值,如果你输入非int类型就会抛异常");
Console.WriteLine("请输入n1的值");
try
{
int n1 = Convert.ToInt32(Console.ReadLine ());
Console.WriteLine("n1={0}",n1);
}
catch
{
Console.WriteLine("输入n1非int类型,出现异常");
}
#endregion
#region Parse的用法
//int.Parse(~~~)
Console.WriteLine("int.Parse类型转换:");
Console.WriteLine("如果你输入int类型,就会正常赋值,如果你输入非int类型就会抛异常");
Console.WriteLine("请输入n1的值");
try
{
int n2 = int.Parse(Console.ReadLine ());
Console.WriteLine("n2={0}",n2);
}
catch
{
Console.WriteLine("输入n2非int类型,出现异常");
}
#endregion
#region int.Try.Parse的用法
//int.TryParse("~~~",out int) 这个式子的值为bool类型
//如果转换成功,那么""里的值就会赋给number,且bool=true
//如果转换失败,那么""里的值就不会赋给number,number会=0,且bool=false
int numberone = 1;
bool b1 = int.TryParse("123",out numberone);
Console.WriteLine(numberone);
Console.WriteLine(b1);
int numbertwo = 1;
bool b2 = int.TryParse("123abc", out numbertwo);
Console.WriteLine(numbertwo);
Console.WriteLine(b2);
#endregion
}
}
}