【问题标题】:how can i completely close my C# program? [duplicate]我怎样才能完全关闭我的 C# 程序? [复制]
【发布时间】:2021-10-20 18:49:22
【问题描述】:

我已经学习了 python,并且正在尝试通过重新创建我的一个基于 python 文本的游戏来学习 C#。在游戏中有一个主要方法,您可以在其中寻找战斗,查看统计数据,硬币,商店,打开或关闭音乐并退出程序。在 python 中它只是 quit() 但我不知道如何在 C# 中停止程序。我问过不和谐的人,但他们无法理解这个问题,并对随机的事情大发雷霆,所以如果能帮助你理解的话,我会展示 python 代码,然后是我的 C# 代码。 蟒蛇:

def Main():
    print("-------------------------------------------")
    choice = input("\n1.fight \n2.Shop \n3.Stats \n4.See coins \n5.music on \n6.music off \n7.quit \nInput:")
    if choice == "1":
        battlestate()

    elif choice == "2":
        Shop()

    elif choice == "3":
        print("-------------------------------------------")
        print("health: ",character.health)
        print("strength: ",character.strength)
        print("armor: ",character.armor)

    elif choice == "4":
        print("-------------------------------------------")
        print("you have: ",character.coins," coins")
        Main()

    elif choice == "4":
        battlestate()

    elif choice == "5":
        music = True
        music = winsound.PlaySound("311 - Love from Afar.wav", winsound.SND_ASYNC | winsound.SND_ALIAS )
        Main()

    elif choice == "6":
        music = False
        music = winsound.PlaySound("311 - Love from Afar.wav", winsound.SND_ASYNC | winsound.SND_ALIAS )
        Main()
        
    elif choice == "7":
        quit()

    else:
        print("i dont understand, please try again!")
        Main()

C#

class Program
    {
        private void Main()
        {
            Console.Write("1.Fight \n7.Quit");
            string choice = Console.ReadLine();
            if (choice == "1")
            {
                BattleState();
            }
            else if(choice == "7")
            {
                
            }
        }

【问题讨论】:

  • 您要退出整个程序?你试过Environment.Exit(0)吗?
  • HCF
  • 您是否观察到当choice 不是"1" 时会发生什么?
  • @Jaskier 谢谢你这个工作,你知道我可以如何存档问题,以便人们可以继续回答但人们可以看到答案吗?
  • 由于尾调用优化,您可能会侥幸逃脱,但递归调用 Main 而不是仅使用循环在这两种语言中都不是好习惯。这就是为什么我们有像while 这样的循环结构。

标签: c#


【解决方案1】:

您无需执行任何操作,程序将自行终止并关闭。真正的问题应该是如何阻止程序关闭。

private void Main()
    { 

        bool running = true;

        Console.Write("1.Fight \n7.Quit");
        while(running) {
           string choice = Console.ReadLine();
           if (choice == "1")
           {
               BattleState();
            } 
           else if(choice == "7")
           {
               running = false;
           }
        }
        Console.WriteLine("Shutting Down...");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多