迭代器变量超出C#的范围

为什么我用C#写这个:

for(int myVar = 0; myVar<10; myVar++)
{
//do something here
}

//then,if I try:
int myVar = 8;
//I get some error that the variable is already declared.

//but if I try:
Console.WriteLine(myVar);
//then I get the error that the variable is not declared.

我最常说的有点混乱.有谁知道为什么C#编译器会这样做?

解决方法

该规则以及其他几个相关规则将在 this blog post of Eric Lippert’s中讨论.

这里违反的特定规则是:

2) It is illegal to have two local variables of the same name in the same local variable declaration space or nested local variable declaration spaces.

特别值得注意的是,关于规则存在的原因如下:

the purpose of all of these rules is to prevent the class of bugs in which the reader/maintainer of the code is tricked into believing they are referring to one entity with a simple name,but are in fact accidentally referring to another entity entirely. These rules are in particular designed to prevent nasty surprises when performing what ought to be safe refactorings.

通过允许你所描述的内容,它可以产生看似良性的重构,例如将for循环移动到另一个声明之后,导致极其不同的行为.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...