【问题标题】:Scope of a variable cfr. Pluralsight C# test变量cfr的范围。 Pluralsight C# 测试
【发布时间】:2017-03-02 10:34:38
【问题描述】:

我正在准备关于 c# 70-483 的微软考试,“还有很长的路要走” 并遵循复数视觉上的 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 loop

  3. 我永远不会超出范围,因为方法是static

  4. 退出for loop

正确答案是 4,但我的答案是 2。 因为在 for 循环之后你仍然可以使用 i。 还是我对“超出范围”的定义不正确?

【问题讨论】:

  • 问题在哪里?
  • 循环后 i 变量再次初始化为零
  • 变量何时超出范围?对不起:)
  • 回答 2 - 在 foreach 之后,而不是在
  • 看起来这是一个旨在吸引您而不是测试知识的问题。退出 for 循环后,foreach 循环将(可能)再次迭代,创建一个新的i 变量。所以技术上在下一次foreach迭代之前退出for循环(因为它不再使用)时它超出了范围,因为你还没有真正退出foreach .

标签: c# scope


【解决方案1】:

这个问题含糊不清,IMO 措辞不好。 C# 中没有变量“超出范围”这样的概念 - 但变量的范围,i 变量的范围是整个 foreach 循环主体,包括for 循环的右大括号和foreach 循环的右大括号之间的一组空语句。 C# 5 规范的相关部分是 3.7:

在局部变量声明(第 8.5.1 节)中声明的局部变量的范围是发生声明的块。在这种情况下,块是foreach 循环的块。

你会写的事实

Console.WriteLine(i);

for 循环之后,它仍然编译表明它仍在范围内。 foreach 循环的每次迭代都使用不同的 i 变量,但在 foreach 循环内的任何地方,i 都在范围内。 (即使在声明之前也是如此 - 您不能使用它,但它仍在范围内。)

我会给出与您相同的答案,作为所问问题的最佳近似值。我建议您向 Pluralsight 发送电子邮件,请他们改进问题。

【讨论】:

    【解决方案2】:

    你的答案 2 是正确的。

    我在 Visual Studio 中使用了以下代码

    class Program
    {
        static void Main(string[] args)
        {
             string[] testdata = { "one", "two", "three", "four"};
             ListCheckFunction(testdata);
             Console.ReadLine();
        }
    
        static void ListCheckFunction(string[] countries)
        {
            foreach (string country in countries)
            {
                int townCount = countries.Count();
                int i = 0;
                for (i = 0; i < townCount; i++)
                {
                    Console.WriteLine(country + " " +i);
                }
                Console.WriteLine(i + " i is still in scope");
            }
        }
    }
    

    它给了我以下输出

    one 0
    one 1
    one 2
    one 3
    4 i is still in scope
    two 0
    two 1
    two 2
    two 3
    4 i is still in scope
    three 0
    three 1
    three 2
    three 3
    4 i is still in scope
    four 0
    four 1
    four 2
    four 3
    4 i is still in scope
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2018-08-01
      • 2021-11-14
      • 2011-12-23
      • 2014-02-13
      • 1970-01-01
      • 2017-09-25
      相关资源
      最近更新 更多