1. using System;
    2. namespace _020_类型转换
    3. {
    4. class Program
    5. {
    6. static void Main(string[] args)
    7. {
    8. #region Convert的用法
    9. //Convert.ToInt32(~~~)
    10. Console.WriteLine("Convert.ToInt32类型转换:");
    11. Console.WriteLine("如果你输入int类型,就会正常赋值,如果你输入非int类型就会抛异常");
    12. Console.WriteLine("请输入n1的值");
    13. try
    14. {
    15. int n1 = Convert.ToInt32(Console.ReadLine ());
    16. Console.WriteLine("n1={0}",n1);
    17. }
    18. catch
    19. {
    20. Console.WriteLine("输入n1非int类型,出现异常");
    21. }
    22. #endregion
    23. #region Parse的用法
    24. //int.Parse(~~~)
    25. Console.WriteLine("int.Parse类型转换:");
    26. Console.WriteLine("如果你输入int类型,就会正常赋值,如果你输入非int类型就会抛异常");
    27. Console.WriteLine("请输入n1的值");
    28. try
    29. {
    30. int n2 = int.Parse(Console.ReadLine ());
    31. Console.WriteLine("n2={0}",n2);
    32. }
    33. catch
    34. {
    35. Console.WriteLine("输入n2非int类型,出现异常");
    36. }
    37. #endregion
    38. #region int.Try.Parse的用法
    39. //int.TryParse("~~~",out int) 这个式子的值为bool类型
    40. //如果转换成功,那么""里的值就会赋给number,且bool=true
    41. //如果转换失败,那么""里的值就不会赋给number,number会=0,且bool=false
    42. int numberone = 1;
    43. bool b1 = int.TryParse("123",out numberone);
    44. Console.WriteLine(numberone);
    45. Console.WriteLine(b1);
    46. int numbertwo = 1;
    47. bool b2 = int.TryParse("123abc", out numbertwo);
    48. Console.WriteLine(numbertwo);
    49. Console.WriteLine(b2);
    50. #endregion
    51. }
    52. }
    53. }