c#基础加强版之方法控制流复习-2变量是否初始化的问题

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

 今天在看老师讲课的时候,发现一个问题,即上上篇学习笔记《小菜学try语句,又被trouble给cathch住了》里提到的变量未被赋值(没有初始化)的问题.以下左边的代码为老师写的代码,MyFirstMehod方法里的num变量声明时也未赋值(没有初始化),可是并没有报错.右边为之前我写的一个ReadInt的方法,编译错误,错误为:使用了为赋值的局部变量Num1.我感觉二者没有什么差别,为什么左边的MyFirstMethod方法没有错误,而右边的ReadInt方法就有错误.

                                                                                                            

static void MyFirstMehod(){
      int num;
      Console.WriteLine("请输入一个数字");
      string str = Console.ReadLine();
      while (true){
         try{
             num=Convert.ToInt32(str);
             break;
          }
          catch{ 
             Console.WriteLine("输入有误,请重输");
              str = Console.ReadLine();
          }
     }   
       Console.WriteLine( num);
  }

  

static void ReadInt(){
   int Num1;
   bool IsNumber = false;
   do{
      Console.WriteLine("请输入一个整数");
      try{
        Num1=Convert.ToInt32(Console.ReadLine());
        IsNumber = true;
        }
      catch{
         Console.WriteLine("您的输入有误");
         }
     }while (IsNumber == false);
     Console.WriteLine(Num1);
  }

 我将ReadInt()方法改为:

        static void ReadInt()
        {
            int Num1;
            do
            {
                Console.WriteLine("请输入一个整数");
                try 
                {
                    Num1 = Convert.ToInt32(Console.ReadLine());
                    break;
                }
                catch
                {
                    Console.WriteLine("您的输入有误");
                }
            } while (true);
            Console.WriteLine(Num1);
        }

这样就不存在Num1没有被赋值的错误了.为什么呢?

我叫小小菜,想要成为一棵大大包心菜.
原文地址:https://www.cnblogs.com/tobecabbage/p/3433110.html