2017-08-10 51 views
-1

我在當前上下文中不存在的最後一行出現錯誤。這是爲什麼?爲什麼不能在方法之外使用寫行,如果方法是靜態的而不是私有的? 由於C#上下文錯誤

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 

    namespace SimpleMethod5 
    { 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       car(); 

      } 

      static void car() 
      { 
       string myCar = "Nissan"; 
       Console.WriteLine(myCar); 
      } 

      Console.Writeline(); 
     } 
    } 

回答

4

一個程序需要一個起點來執行,並在C#控制檯程序它是Main()方法。然後,執行遵循Main()指令的路徑,也就是說,如果它調用一個繼續執行的函數,並且控制再次返回到Main()等等。(當然這個解釋考慮單線程程序)。

所以你不能寫一個方法調用(這是什麼Console.WriteLine()是)在一個類內,因爲程序不知道什麼時候調用它。