为什么这个程序的底部是 static void Main(string[] args)?

Why is static void Main(string[] args) at the bottom of this program?

我正在学习 C#,它在教程中说 "When you run your programme, C# looks for a Method called Main. It uses the Main Method as the starting point for your programmes. It then executes any code between those two curly brackets. "

但是在另一个教程网站上有一段代码说

using System;
namespace RectangleApplication
{
   class Rectangle 
   {
     // member variables
     double length;
     double width;

     public void Acceptdetails()
     {
        length = 4.5;    
        width = 3.5;
     }

     public double GetArea()
     {
        return length * width; 
     }

     public void Display()
     {
        Console.WriteLine("Length: {0}", length);
        Console.WriteLine("Width: {0}", width);
        Console.WriteLine("Area: {0}", GetArea());
     }
   }

class ExecuteRectangle 
{
  static void Main(string[] args) 
     {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine(); 
      }
   }
}

在其他方法下面使用 Main 方法。 (我是新手,所以我假设 public void acceptdetails、get area、display 都是方法)。我的问题是,为什么它不在命名空间下方的右上角?我把这个方法放在那里,它的工作原理是一样的,并检查了这里的其他帖子,它说也许作者只是想强调其他事情,但我不完全明白为什么。

把它放在哪里并不重要。 Main() 始终是程序首次运行时的入口点。诸如 Main() 之类的函数可以在代码中的任何位置,并且编译器将从那里开始 运行,假设它可以编译并且语法没问题。

看来上述代码的作者故意将 Main() 函数放在该源代码的底部来说明这一点。

Main() 是一个 'special' 函数,作为程序的入口点,即使它没有出现在代码清单的最前面。在上面的代码中,程序员将 Rectangle class 的声明放在最前面,但这并不影响先运行哪段代码。 Main() 首先运行。这就是语言设计的工作方式。

我猜你的疑惑是,如果 c# 逐行执行语句,为什么 main 方法不在开头。好吧,它不一定是因为那是编译器为你做的。编译器查找入口点以找出执行的第一行。它通过名称 "main" 方法查找它。这就是为什么您的应用程序中不能有多个方法的原因之一。因为编译器会“困惑”,无法决定先进入哪里。

并且一旦进入main方法,就开始逐行执行。如果它找到任何方法调用,它会再次开始寻找方法名称,进入方法,开始逐行执行并返回到它离开的地方的主要方法。

因此,正如您可能已经看到的,无论您将代码放在代码文件中的什么位置,编译器仍然会逐行执行。

当然,我省略了并行编程或异步操作的高级案例。