C# public void static Main(String[] args){} 和 public int static Main(String[] args) 两个重载方法如何协同工作?

Ahm*_*aaj 1 .net c#

CLR 如何知道要调用哪个方法,因为它们返回不同的值(一个是 void,另一个是 int)?从重载的意义上来说,这也是不对的,具有相同参数但返回类型不同的方法。

例子:

class Program
{
    static int Main(String[] args) //Main with int return type but Parameter String[] args
    {
            return 0;
    }

    /* this main method also gonna get called by CLR even though return type void  and Same parameter String[] args.
   static void Main(String[] args) //Main with int return type but String[] args
   {

   } */

    private static void func(int one)
    {
        Console.WriteLine(one);
    }

    private static int func(int one) //compiler error. two overloaded method cant have same parameter and different return type. 
    {
        return 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

但 main 方法不维护重载规则。

ami*_*ama 5

在.NET 中,一个可执行文件只能有一个入口点,即只允许有一个Main 方法。更具体地说,仅当签名与以下 2 项中的任何一个匹配并且该方法是静态的时,Main 方法才被视为入口点。

  1. 主要(字符串[])
  2. 主要的()

如果您提供的 main 方法的签名与上述两个方法不同,则它不被视为 Main 方法。所以,下面的代码是允许的,

class Program
{
    static void Main ()          //Entry point
    {
    } 

    static void Main(int number)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的代码无法编译,因为它在两个地方找到了匹配的签名。

class Program
{
    static void Main ()          //Entry point
    {
    } 

    static void Main(String[] args)   //another entrypoint!!! Compile Error
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的代码也无法编译,因为根本没有入口点,

class Program
{
    static void Main (int a)      //Not an Entry point 
    {
    } 

    static void Main(float b)    //Not an entry point
    {
    }
}
Run Code Online (Sandbox Code Playgroud)