2017-03-02 92 views
4

我正在爲我的微軟考試準備c#70-483,「還有很長的一段路要走」 以及關於multiplesight的C#路徑。 做完這個測試後,回顧一下我的不正確答案,我找到了這個。變量cfr的範圍。 Pluralsight C#測試

2.Consider下面的代碼:

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,但由於之後的for循環你仍然可以使用我我的答案是2 。 或者我的「超出範圍」的定義不正確?

+4

問題在哪裏? –

+0

循環後i變量再次初始化爲零 –

+0

變量何時超出範圍?對不起:) –

回答

8

的問題是含糊不清,嚴重的措辭IMO。在C#中沒有變量「超出範圍」這樣的概念 - 但是的一個變量的作用域,而i變量的作用範圍是整個foreach循環體,包括空集合之間的語句在for循環的結束花和foreach循環的結束花。 C#5規範的相關部分是3.7:

局部變量聲明(§8.5.1)中聲明的局部變量的範圍是發生聲明的塊。在這種情況下,該塊是foreach循環的塊。

,你可以在for循環後寫

Console.WriteLine(i); 

,它仍然編譯表明,它仍然在範圍內的事實。所述foreach循環的每次迭代使用不同i變量,但處處foreach循環內,i是在範圍內。 (這是真實的,即使其聲明之前 - 你可以不使用它,但它仍然在範圍之內。)

我已經給出了相同的答案你,是最好的逼近對方的問題。我建議你發郵件給Pluralsight,讓他們改進這個問題。

0

你的答案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