Calling Main( ) from another class

╄→гoц情女王★ 提交于 2019-12-31 02:25:26

问题


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)


来源:https://stackoverflow.com/questions/6723558/calling-main-from-another-class

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