C#:循环内变量声明
下面的代码正确吗?
foreach (int i in MyList)
{
MyObject m;
}
可以多次声明一个变量吗?
Is the following code correct?
foreach (int i in MyList)
{
MyObject m;
}
Can you declare a variable more than once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不会多次声明它。变量有一个“作用域”,
m
变量的作用域在下一次迭代之前结束于}
末尾。You are not declaring it more than once. Variables have a "scope", and the scope of the
m
variable ends at the end}
before the next iteration.是的。
如果我没记错的话,在执行时,它只声明一次,但该变量会重复使用,直到作用域结束(而不是每个循环结束)。
Yes.
If I remember my C# correctly, when executed, it is only declared once, but the variable is re-used until the end of the scope (not the end of each loop).
您可以在循环内声明变量。如果仅在循环内需要它,则出于代码可读性的考虑更可取。它可能会损害性能,但您只需要担心是否声明和实例化相关变量的成本很高,或者您的列表非常大。
You can declare a variable inside a loop. If it is only needed inside the loop, it is preferable for code readability. It can possibly be detrimental to performance, but you would only need to worry about that if the variable in question was expensive to declare and instantiate, or your list was extremely large.