Calling Main( ) from another class

2019-02-25 12:37发布

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.

标签: c# main
4条回答
虎瘦雄心在
2楼-- · 2019-02-25 12:40

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

查看更多
Deceive 欺骗
3楼-- · 2019-02-25 12:43

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

查看更多
时光不老,我们不散
4楼-- · 2019-02-25 12:46

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.

查看更多
该账号已被封号
5楼-- · 2019-02-25 13:03

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)
查看更多
登录 后发表回答