gpt4 book ai didi

c# - 变量cfr的范围。 Pluralsight C# 测试

转载 作者:太空狗 更新时间:2023-10-30 00:30:03 26 4
gpt4 key购买 nike

我正在准备有关 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 何时超出范围?答案:

  1. 退出 ListTowns() 方法。

  2. 退出 foreach 循环

  3. 我从不超出范围,因为该方法是静态

  4. 退出 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com