how to call “ static void Main(string[] args) ”in the class again

走远了吗. 提交于 2019-12-02 03:47:32
JMK

Just call the method again, passing in the same arguments that where passed in initially, also try to avoid using goto if you can:

if (selectedOption == "y")
{
    // howto call  static void Main(string[] args) here agin so that the program start itself from the start point
    Main(args);
}    

Firstly, your label is incorrect. The end of a label should have a colon character :.. so your label should have been this:

StartPoint:

However:

You should just loop until a condition is met. In this case.. the condition is to not restart:

bool running = true;

while (running) {
    /* 
     * all of your other code
     * should go here
     */
    if (selectedOption != "y") {
        running = false;
    }
}

You realy should not use a goto or call your Main again (recursion), do while is a better solution to repeat your logic muliple times:

    string selectedOption;
    do {
        Write();
        string name = Console.ReadLine();
        Write();
        string name1 = Console.ReadLine();
        Write();
        string name2 = Console.ReadLine();
        Write();
        string name3 = Console.ReadLine();

         Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);

         Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
         selectedOption = Console.ReadLine();
      } while (selectedOption == "y")
      Console.ReadKey();

Try put the code that you will execute outside the main class in another method like

void execute()
{
        Write();
        string name = Console.ReadLine();
        Write();
        string name1 = Console.ReadLine();
        Write();
        string name2 = Console.ReadLine();
        Write();
        string name3 = Console.ReadLine();

         Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);

         Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
         string selectedOption = Console.ReadLine();

}

then in the main

static void Main(string[] args)
{
    bool run = true
    while(run){
       execute()
       Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
        selectedOption = Console.ReadLine();
        if (selectedOption == "n")
        {
             run = false;
        }    
    }
}

something like this :

static void Main(string[] args)
            {      
                string selectedOption = "";

                 do 
                 {

                               ...........

                 }
                 while (selectedOption == "y")

                 if (selectedOption == "n")
                 {
                   //Terminate the Program
                  }

             } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!