切换C#后如何不退出方法

How to not exit out of method after switch C#

所以我想知道如何使一个包含 switch 语句的方法在 case 完成后不关闭。这是我所做的。

public static int Store(int cashyo)
    {
        int open = 1;

        while (open != 0)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("What would you like to buy?");
            Console.ForegroundColor = ConsoleColor.Red;
            string option = Console.ReadLine();

            switch (option)
            {
                case "bye":
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Leaving store.");
                    Thread.Sleep(1500);
                    open = 0;
                    break;

                case "list":
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Bike");
                    break;

                case "bike":
                    Console.ForegroundColor = ConsoleColor.Green;
                    if (cashyo >= 300)
                    {
                        Console.WriteLine("Purchased Bike for 300 USD!");
                        return (cashyo-3000);
                    }
                    else
                    {
                        Console.WriteLine("Canot purchase Bike. Insufficient amount of funds.");
                        return cashyo;
                    }
                    break;

            }
            return cashyo;
        }
        return cashyo;
    }

cashyo 是 main 中实际使用的货币的虚拟变量。我想这样做,如果我输入“自行车”,它会购买自行车,然后再问我我想做什么,因为 open 仍然不是 0。

删除紧跟在开关后面的 return 语句,并删除自行车部分中的 2 个 return(您还需要在减去的地方设置新的 cashyo 值)。还注意到您正在检查 300,但在自行车部分减去 3000。

Return 意思是“离开程序”,所以它不会因为你告诉它结束而循环回来。