因为 test 声明, 和赋值靠着

解决方案 »

  1.   

    在声明时写成 string test=string.Empty;虽然你在for语句内赋了值,但在编译时,程序是不会for语句内的代码能否执行到的.
    因此会认为你没有赋值就使用了.
      

  2.   

    namespace ConsoleApplication1 

        class Program 
        { 
            static void Main(string[] args) 
            { 
                int i; 
               string test="";//第一行 
                for (i = 0; i < 10; i++) 
                { 
                    test = "line"; 
                    Console.WriteLine(test); 
                } 
                Console.WriteLine(test ); 
                Console.ReadKey(); 
            } 
        } 
    } 千万记住,C#变量要赋初值
      

  3.   

    下面的那个等于给test赋了初值“line”而上面的那个没有赋初值,就直接进行下面的逻辑了,编译器会提示你那个警告,为了保持良好编程习惯,你就设置个初值吧,null,string.empty都行
      

  4.   

     Use of unassigned local variable 'test'  编译不能通过,怎么会没有关系呢?
      

  5.   

    赞成这个。。现在是找问题,不是说编程习惯的问题。实现不行你看下ildasm中的情况就知道了
      

  6.   

    如果没有初始值
    CLR 编译的时候 会为你的 string test =null;
    后面继续赋值的话还是要成功的,不过 会警告...使用了为赋值的test
      

  7.   

    目前编译器不会自动把你的循环展开,
    它不能确保循环里的代码一定会运行到。
    void MyMethod(int c)
    {
       for(int i=0; i<c; i++)
       {
          // 谁能确定这行一定运行的到? 如果c=0呢?
       }
    }因此,编译器不认可在循环,条件分支等中的赋初值代码,
    并产生“用了未赋值的局部变量”的编译错误。
      

  8.   


    这句话容易造成误解。编译器还是很聪明的,当所有条件分支都能给变量赋初值,
    该种初始化将被认可,比如下面的代码。
    但是,如果条件分支不能涵盖所有情况,初始化同样不被认可,比如反注释下面代码第6行后的情况。string str;
    if (Environment.TickCount % 2 == 1)
    {
        str = "hello";
    }
    else //if (Environment.TickCount %2 == 0 )
    {
        str = "world";
    }
    MessageBox.Show( str );
      

  9.   

           static void Main(string[] args)
           {
                int i;
                string test;//第一行 
                for (i = 0; i < 10; i++)
                {
                    test = "line";
                    Console.WriteLine(test);
                }
                Console.WriteLine(test);
                Console.ReadKey(); 
            }注意如果使用局部变量则必须赋初始值,如果使用全局变量 则不需赋初始值
             private int i;
            private string str;
            static void Main(string[] args)
            {
                int i;
                string test;//第一行 
                Program p = new Program();
                Console.WriteLine(p.i + "     " + p.str);
            }贴主的第二种情况
    static void Main(string[] args) 
            { 
                //int i; 
                string test;//第一行 
              // for (i = 0; i < 10; i++) 
                { 
                    test = "line"; 
                    Console.WriteLine(test); 
                } 
                Console.WriteLine(test ); 
                Console.ReadKey(); 
            } 
    注视了循环test 就复制了