我可以在“for”中定义字符串变量吗?环? [英] Can I define string variable in "for" loop?

查看:98
本文介绍了我可以在“for”中定义字符串变量吗?环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿那里,起初,我应该说:我是初学者,我正在学习

i有一个问题,我可以在for循环中定义字符串变量吗? ?但我这样做我的程序不起作用但是visual studio没有错误,为什么???



我尝试了什么:



但我这样做我的程序不起作用但是visual studio没有错误,为什么???

Hey there, at first, i should say: "i'm a beginner, i'm learning"
i have a question, can i can i define string variable in "for" loop?? but i do that my program doesn't work but visual studio doesn't error, why???

What I have tried:

but i do that my program doesn't work but visual studio doesn't error, why???

推荐答案

您可以在的主体中为循环定义字符串变量而不会出现任何问题:

You can define a string variable in the body of a for loop without problems:
for (int i = 0; i < 10, i++)
   {
   string myString = i.ToString();
   ...
   }

但是你只能使用那个体内的字符串 - 你不能在循环之外使用它,因为它是超出范围而不能再看到。变量只能在声明它们的花括号块内使用:

But you can only use the string within that body - you cannot use it outside the loop as it is "out of scope" and can no longer be seen. Variables can only be used inside the "curly bracket block" within which they are declared:

{ // scope of i1 starts here.
...
int i1 = 1;
...
// i2 cannot be used here.
   {  // scope of i2 starts here.
   ...
   int i2 = 2;
   ...
   } // scope of i2 ends here.
// i2 cannot be used here.
...
}  // scope of i1 ends here.





您还可以将字符串定义为的循环控制变量,用于循环:



You can also define a string as the loop control variable of a for loop:

for (string s = "0"; s.Length < 10; s += "0")
    {
    Console.WriteLine(s);
    }

但显然,你不能在增量部分使用++ s或s ++。 s的范围保持不变 - 如果循环外的代码不可见。



如需更多帮助,我们需要更多信息究竟是你编写的代码!

But obviously, you can't use ++s or s++ in the "increment" section. The scope of "s" remains the same - if it not visible to code outside the loop.

For any more help, we'd need a lot more info on exactly what code you have written!


这篇关于我可以在“for”中定义字符串变量吗?环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆