2012-07-31 85 views
7

問題是,當我添加新類後,當我構建解決方案時出現錯誤。什麼可能是錯誤的?爲我的項目添加了一個新類,並且出現錯誤,說Program.Main()有多個條目爲什麼?

在Form1我還沒有任何代碼。

剛添加了新類:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using OpenHardwareMonitor.Hardware; 

namespace OpenHardwareMonitorReport 
{ 

    class Program 
    { 

     static void Main(string[] args) 
     { 
      Computer computer = new Computer(); 
      computer.Open(); 

      var temps = new List<decimal>(); 
      foreach (var hardware in computer.Hardware) 
      { 
       if (hardware.HardwareType != HardwareType.CPU) 
        continue; 
       hardware.Update(); 
       foreach (var sensor in hardware.Sensors) 
       { 
        if (sensor.SensorType != SensorType.Temperature) 
        { 
         if (sensor.Value != null) 
          temps.Add((decimal)sensor.Value); 
        } 
       } 
      } 

      foreach (decimal temp in temps) 
      { 
       Console.WriteLine(temp); 
      } 
      Console.ReadLine(); 
     } 
    } 
} 

然後,我看到的Program.cs和錯誤上的Main()

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 

namespace NvidiaTemp 
{ 
    static class Program 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main() 
     { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      Application.Run(new Form1()); 
     } 
    } 
} 

Error 2 Program 'D:\C-Sharp\NvidiaTemp\NvidiaTemp\NvidiaTemp\obj\x86\Debug\NvidiaTemp.exe' has more than one entry point defined: 'NvidiaTemp.Program.Main()'. Compile with /main to specify the type that contains the entry point. D:\C-Sharp\NvidiaTemp\NvidiaTemp\NvidiaTemp\Program.cs 14 21 NvidiaTemp 
+1

你現在有兩個'Main'。 – 2012-07-31 19:43:35

+0

謝謝修復tnx。 – user1544479 2012-07-31 19:47:34

回答

10

A C#程序只能有一個Program.Main()。 Main是程序啓動時運行的第一個方法,因此編譯器需要知道哪一個是真正的,而如果有兩個則不能。

看起來你正在製作Windows應用程序。您應該將代碼添加到現有的主體中,或者將其添加到由主窗體觸發的事件處理程序中。

5

一個.NET程序應該只有一個靜態方法Main

你有兩個,編譯器不知道使用哪一個。

重命名粘貼一個,除非你想是入口點的應用程序(在該情況下,其它的重命名),或編譯使用/main開關指定傳遞應用其中Main方法使用。

更多細節參見Main() and Command-Line Arguments (C# Programming Guide)上MSDN:

的主要方法是一個C#控制檯應用程序或窗口應用的入口點。 (庫和服務不需要Main方法作爲入口點)。當應用程序啓動時,Main方法是第一個被調用的方法。

在C#程序中只能有一個入口點。如果您有多個具有Main方法的類,則必須使用/ main編譯器選項編譯程序,以指定將哪個Main方法用作入口點。有關更多信息,請參閱/ main(C#編譯器選項)。

(重點煤礦)

1

你有兩個主要方法,這就是爲什麼你得到這個錯誤。

MSDN - Main Method

中只能有一個C#程序的一個入口點。如果您的更多 比擁有主要方法的一個類,則必須使用/ main編譯器選項編譯程序 ,以指定使用哪個主要方法作爲 入口點。

9

其他人指出你有兩個static void Main方法。有兩個簡單的修復方法,一個很明顯,一個還沒有特別提及:

  1. 將一個重命名爲其他任何東西,例如Main1,NotMain
  2. 要設置@Habib提到的/ main編譯器選項,只需右鍵單擊解決方案資源管理器中的項目節點,選擇屬性,然後在應用程序部分的下拉列表中選擇「啓動對象」。

通過解決方案2,您可以在不需要編譯器發出抱怨的情況下在不同的類中使用相同的Main(string[] args)簽名。

+3

終於有人指出如何使用Visual Studio調整'/ main'(......他們在命令行中認真編譯他們的C#項目?) – mmcrae 2015-11-10 20:45:19

1

如果修復了錯誤並且Visual Studio仍然給出了錯誤消息,那麼刪除輸出文件夾(默認爲「bin」和「obj」)並重建項目是值得的。在我的情況下,只需點擊「重建」沒有幫助。

相關問題