static void main()
{
   
int i;
   
for(i=0;i<10;i++)
   { 
      
string text="Line"+Covert.ToString(i);
      Console.WriteLine(
"{0}",text);
   }
   Console.WriteLine(
"Last text output in loop:{0}",text);
   Console.ReadKey();
}

字符串常量text是for循环里面的局部变量,这段代码不能编译,在循环外部调用了该变量,超过了循环的作用域,修改代码如下:

static void main()
{
   
int i;
   
string text;
   
for(i=0;i<10;i++)
   { 
      
string text="Line"+Covert.ToString(i);
      Console.WriteLine(
"{0}",text);
   }
   Console.WriteLine(
"Last text output in loop:{0}",text);
   Console.ReadKey();
}

这段代码也会失败,是因为声明的变量没有初始化,循环内的初始化在循环结束后失效,修改代码如下:

static void main()
{
   
int i;
   
string text="";
   
for(i=0;i<10;i++)
   { 
      
string text="Line"+Covert.ToString(i);
      Console.WriteLine(
"{0}",text);
   }
   Console.WriteLine(
"Last text output in loop:{0}",text);
   Console.ReadKey();

相关文章:

  • 2021-10-02
  • 2021-12-03
  • 2021-10-20
  • 2021-08-28
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2022-12-23
  • 2022-02-06
  • 2022-12-23
  • 2021-05-18
相关资源
相似解决方案