【发布时间】:2012-03-12 07:23:13
【问题描述】:
private void Abc()
{
string first="";
ArrayList result = new ArrayList();
ArrayList secResult = new ArrayList();
foreach (string second in result)
{
if (first != null)
{
foreach (string third in secResult)
{
string target;
}
}
string target;//Here I cannot decalre it. And if I don't declare it and
//want to use it then also I cannot use it. And if it is in if condition like
//the code commented below, then there is no any complier error.
//if (first != null)
//{
// string target;
//}
}
}
我不明白:为什么我不能在foreach 循环之外声明变量,因为编译器给出了一个变量已经声明的错误。 foreach(以及 target 变量)的范围已经超出了我声明这个新变量的位置。
【问题讨论】:
-
这是由选择 - 编译器希望帮助您避免一些非常常见的错误。例如,F# 确实允许这样的事情(即使在同一范围内),但它有助于不可变/功能范式
-
虽然这是个好问题,但这里有很多重复项。其中之一:stackoverflow.com/questions/2059210/….