Scope of iteratee too wide
Possible Duplicate:
Why can’t a duplicate variable name be declared in a nested local scope?
我注意到以下代码没有编译。快速修复方法是将外部变量
难道我不能在循环之外重用名称
1 2 3 4 5 | String aggregate = String.Empty; foreach (Thing thing in things) aggregate += thing.Value; Thing thing = new Thing(); |
Shouldn't I be able to reuse the name thing outside the loop? Why?
问题是最后一行中变量的范围向上扩展了…它覆盖了整个街区。所以问题实际上是,您不能为循环声明
从C 4规范的8.5.1节开始:
The scope of a local variable declared in a local-variable-declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local-variable-declaration of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.
最后一句话就是你的代码违反的那句话。
只是用不同的名字。
事实上,令人惊讶的是,变量的范围比您预期的要宽。尝试此代码。
1 2 3 4 5 | String aggregate = String.Empty; foreach (Thing thing in things) aggregate += thing.Value; foreach (Thing thing in things) aggregate += thing.Value; |
它编译得很好。但是,如果您像您那样在外部声明