关于c#:iteratee的范围太宽


Scope of iteratee too wide

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Why can’t a duplicate variable name be declared in a nested local scope?

我注意到以下代码没有编译。快速修复方法是将外部变量thing回忆成其他变量,但后来我开始思考并意识到内部范围应该在foreach循环中结束。我肯定不能在它之外使用内部变量。

难道我不能在循环之外重用名称thing吗?为什么?

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?

问题是最后一行中变量的范围向上扩展了…它覆盖了整个街区。所以问题实际上是,您不能为循环声明thing变量,因为它与已经在作用域中的另一个变量冲突。

从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;

它编译得很好。但是,如果您像您那样在外部声明thing,则声明范围是向外的。有时也会让我感动。:)