Visual Studio 运行 如何通过我的代码?

How does Visual Studio run through my code?

我最近决定自学编码(使用 Microsoft Virtual Academy 等免费在线工具),并且我决定 C# 将作为我的起始语言。

和大多数初学者一样,我有一个非常基本的问题,我似乎无法找到答案(可能是因为它太简单了)。我正在使用 Visual Studio,我只是想通过我编写的代码了解该软件如何 运行。

这是我的猜测:我相信当我 运行 代码时,它只会执行 "class Program1" 中的操作,因为那是代码中的第一个 class。一旦它到达该块的末尾,它就不会执行任何其他操作,因此它会关闭控制台(或者从技术上讲,我在按下 ENTER 时关闭了控制台)。

最初我认为它也应该 运行 到 "class Program2",但在尝试后发现它没有按预期工作,我被引导相信有任何 class 功能就像我想要的那样(除了列出的第一个 - 在这种情况下为 Program1)它需要被调用。我对 VS 如何通过我的代码 运行 的理解是否正确?对于术语中的任何混淆,我也深表歉意。提前致谢!

示例代码:

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

namespace Testing
{
    class Program1
    {
        static void Main(string[] args)
        {
            Console.WriteLine("I'm Text!");
            Console.ReadLine();
        }
    }
    class Program2
    {
        static void Main2(string[] args)
        {
            Console.WriteLine("I'm More Text!");
            Console.ReadLine();
        }
    }
}

你基本上是正确的。默认情况下,它会尝试找到一个签名为 static void Main(string[] args) 的方法在启动时执行(return 类型的 int and/or 没有参数也是可以接受的)。

The Main method is the entry point of a C# console application or windows application. (Libraries and services do not require a Main method as an entry point.). When the application is started, the Main method is the first method that is invoked.

https://msdn.microsoft.com/en-us/library/acy3edy3.aspx

我说 "by default" 是因为您确实可以有不止一种具有该签名的方法(在不同的 类 中)。如果这样做,您会收到编译器错误

Error 1 Program 'c:...\obj\Debug\MyProgram.exe' has more than one entry point defined: 'MyProgram.Program.Main(string[])'. Compile with /main to specify the type that contains the entry point.

在这种情况下,您可以使用编译标志 /main 来指定应该从哪里开始执行。