2016-06-20 92 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

相關問題