Calling Main( ) from another class

2019-02-25 12:35发布

问题:

I have a class named TestMaze. I have another class named DisplayHome which has a method called gameOver():

public void gameOver()
    {
        Console.Write("GAME OVER!");
        Console.Write("Play Again? Y/N");
        if(char.ToLower(Convert.ToChar(Console.Read())=='y')
            //Main()
        else
            Environment.Exit(1);
    }

How can I call the Main method?
PS. they have the same namespace. I just need to know how can I call the Main method again.

回答1:

You should have a Play() method inside your Main... and GameOver() should call Play() if user enters 'y'.



回答2:

Refactor your code. Move whatever needs to be called into another function, and call it from both, main, and gameOver.



回答3:

Assuming Main is a static class method (which I'd imagine it is) you can simply use MyClass.Main(/*relevant args*/) - beware of course that it's going to be a fresh instantiation, it won't share any non-static variable data.

A possibly better solution however would be to put all your code into a separate class which is invoked/instantiated from Main() - your program can then pass a boolean back to the actual executable Main which will be used to decide whether or not to exit or loop.



回答4:

If your Main method is in the TestMaze class just do:

TestMaze.Main(" supply arguments ")
For example

string[] args=new string[]{"New Game","1"}
TestMaze.Main(args)

Usually Main is found in the Program class so do:

Program.Main(args)


标签: c# main