2016-06-20 83 views
0

CLR如何知道调用哪个方法,因为它们返回不同的值(一个是无效的,另一个是int)?在重载意义上,这也是不正确的,一种具有不同返回类型的相同参数的方法。C#public void static Main(String [] args){}和public int main(String [] args)两个重载的方法一起工作吗?

例如:

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; 
    } 
} 

但主要方法是不维持重载规则。

+1

请提供一个代码示例。 – Kapol

回答

4

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

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

如果你提供的主方法,其签名是由两个以上不同,它不被认为是主要的方法。所以,下面的代码是允许的,

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

    static void Main(int number) 
    { 
    } 
} 

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

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

    static void Main(String[] args) //another entrypoint!!! Compile Error 
    { 
    } 
} 

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

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

    static void Main(float b) //Not an entry point 
    { 
    } 
} 
+0

此外,只是一般情况下,当重载时,这些方法必须不仅仅是返回类型。 – Kevin

相关问题