为什么要在foreach循环中声明数据类型?

问题描述:

全部:

为什么我们需要在foreach循环中提及变量的数据类型?

All:

Why do we need to mention datatype of a variable inside foreach loop ?

foreach(string strName in strFilePath)
{
   //Operations here
}



为什么我们不能在外面声明它?



Why cannot we declare it outside?

string strName = ""; 
foreach (strName in strFilePath)
{
   //Operations here
}

因为在foreach循环中使用的变量很特殊-它的作用域有限并且是只读的.

该声明提醒(如果您愿意)它是一个特殊值,而不应被视为常规"变量.它将变量的范围限制为仅循环的范围,而没有复杂的伪装.否则,这意味着可以更改只读状态(不能更改),或者可以引用循环开始之前的任何初始值(不能这样做).
Because the variable used in a foreach loop is special - it has limited scope and is read only.

The declaration is a reminder (if you like) that it is a special value, and not to be treated like "normal" variables. It limits the scope of the variable to just the extent of the loop without complex machinations. Otherwise, it would imply that the read-only status could be changed (which it can''t) or that any initial value from before the loop began could be referenced (which it can''t).