我正在准备有关 c# 70-483 的 Microsoft 考试,“还有很长的路要走” 并遵循 pluralsight 上的 C# 路径。 在完成测试并查看我的错误答案后,我想到了这个。
2.考虑以下代码:
static void ListTowns(string[] countries)
{
foreach (string country in countries)
{
int townCount = GetTownCount(country);
int i = 0;
for (i = 0; i < townCount; i++)
{
Console.WriteLine(GetTownName(country, i));
}
}
}
变量 i 何时超出范围? 答案:
退出
ListTowns()
方法。退出
foreach 循环
我从不超出范围,因为该方法是
静态
。退出
for 循环
正确答案是 4,但我的答案是 2。 因为在 for 循环之后你仍然可以使用 i。 还是我对“超出范围”的定义不正确?
最佳答案
问题含糊不清,IMO 措辞不当。在 C# 中没有变量“超出范围”这样的概念 - 但是变量的范围,i
变量的范围是整个foreach
循环体,包括 for
循环的右括号和 foreach
循环的右括号之间的空语句集。 C# 5 规范的相关部分是 3.7:
The scope of a local variable declared in a local-variable-declaration (§8.5.1) is the block in which the declaration occurs. In this case, the block is the block of the
foreach
loop.
你会写的事实
Console.WriteLine(i);
在 for
循环之后它仍然编译表明它仍在范围内。 foreach
循环的每次迭代都使用不同的 i
变量,但是在 foreach
循环的任何地方,i
都在范围。 (即使在声明之前也是如此 - 您不能使用它,但它仍在范围内。)
我会给出与您相同的答案,作为对所问内容的最佳近似。我建议您向 Pluralsight 发送电子邮件,要求他们改进问题。
关于c# - 变量cfr的范围。 Pluralsight C# 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552971/