簡體   English   中英

我如何從另一個類調用 Main?

[英]How do I call Main from another class?

所以我正在制作一個 C# 控制台程序,它是一個簡單的計算器,我只是在學習 C#。

這是我想調用 main 的地方:

if (info.Key == ConsoleKey.Escape)
{
    Environment.Exit(0);
}
else
{
}

我想為加法、減法、乘法和除法類調用 main,這樣它就會回到開始的地方,它要求“按‘A’進行加法”等。

我試着把“Main();” 在其他但它給我和錯誤說“沒有給出與'Program.Main(String [])的所需形式參數'args'相對應的參數”

我怎么能在這個類中調用 main 以便它轉到 main 的開始?

您不會自己調用Main它被用作應用程序的入口點。 通常你會調用其他方法,例如:

static void Main(string[] args)
{
   while (true) 
   {
        Console.Write("> ");
        string command = Console.ReadLine().ToLower();

        if (command == "add")
        {
            Add(); // Call our Add method
        }
        else if (command == "subtract")
        {
            Subtract(); // Call our Subtract method
        }
        else if (command == "multiply")
        {
            Multiple(); // Call our Multiply method
        }
        else if (command == "exit")
        {
            break; // Break the loop
        }
   }
}

static void Add()
{
    // to-be-implemented
}

static void Subtract()
{
    // to-be-implemented
}

static void Multiply()
{
    // to-be-implemented
}

這里要注意的另一件事是Main(string[] args)args參數包含在命令行args控制台應用程序的參數數組。

如果打電話給Main自己,你將需要一個值傳遞到這一點,例如:

Main(null); // No array
Main(new string[0]); // An empty array
Main(new string[] {}); // Another empty array
Main(new string[] { "Something" }); // An array with a single entry

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM