为什么foreach循环内的局部变量与循环外声明的变量冲突? [英] Why does local variable inside foreach loop conflict with variable declared outside the loop?

查看:52
本文介绍了为什么foreach循环内的局部变量与循环外声明的变量冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

List<string> things = new List<string>();

foreach (string thing in things)
{
    string foo = thing.ToUpper();
}

string foo = String.Empty;

为什么编译器会抱怨foo被两次声明?确定在foreach循环中声明的实例仅在循环范围内有效吗?

Why does the compiler complain that foo is declared twice? Surely the instance declared in the foreach loop is only valid within the scope of the loop?

推荐答案

虽然您只能在声明后引用外部 foo ,但在函数的开头分配了本地变量,这意味着内部的 foo 将遮盖外部的,即使尚未声明.

While you can only refer to the outer foo after you declared it, locals are allocated at the beginning of a function which means the inner foo will overshadow the outer one, even if it hasn't been declared yet.

这篇关于为什么foreach循环内的局部变量与循环外声明的变量冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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