在C#上再次运行该函数

时间:2018-11-01 11:52:02

标签: c# class switch-statement repeat

我有一个带有switch的简单代码。 问题是在任何情况下完成后或在默认情况下,代码都将终止。 我想要得到的是,完成后会问“您是否想重复”这个问题,如果答案是Y,它将再次运行Main,如果它是N,则终止,依此类推。 我尝试过do ...而又没有其他建议吗?

我确信它应该看起来像这样:

Console.WriteLine("Would you like to repeat? Y/N");

input = Console.ReadKey().KeyChar;

if (input == 'Y') {...}

代码:

class Switch
{
    static void Main()
    {
        Console.Write("Enter your selection (1, 2, or 3): ");
        string s = Console.ReadLine();
        int n = Int32.Parse(s);

        switch (n)
        {
            case 1:
                Console.WriteLine("Current value is {0}", 1);
                break;
            case 2:
                Console.WriteLine("Current value is {0}", 2);
                break;
            case 3:
                Console.WriteLine("Current value is {0}", 3);
                break;
            default:
                Console.WriteLine("Sorry, invalid selection.");
                break;
        }

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

4 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

class Switch
    {
    static void Main()
    {
    bool repeat = false;
    do {
        repeat = false;
        Console.Write("Enter your selection (1, 2, or 3): ");
        string s = Console.ReadLine();
        int n = Int32.Parse(s);

        switch (n)
        {
            case 1:
                Console.WriteLine("Current value is {0}", 1);
                break;
            case 2:
                Console.WriteLine("Current value is {0}", 2);
                break;
            case 3:
                Console.WriteLine("Current value is {0}", 3);
                break;
            default:
                Console.WriteLine("Sorry, invalid selection.");
                break;
        }
        Console.WriteLine("Would you like to repeat? Y/N");
        input = Console.ReadKey().KeyChar;
        repeat = (input == 'Y');

    }while(repeat);
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
    }

如果用户要重复操作,请添加一个do while循环,并在最后添加一个检查。

答案 1 :(得分:1)

让我们简化问题:提取方法

   private static void MyRoutine() {
     Console.Write("Enter your selection (1, 2, or 3): "); 

     String input = Console.ReadLine();
     int n = 0;

     // User Input validation: we want integer value (int.TryParse) in the desired rang
     if (!int.TryParse(input, out n)) {
       Console.WriteLine("Sorry, invalid selection. Integer value expected");  

       return;
     }
     else if (n < 1 || n > 3) {
       Console.WriteLine("Sorry, invalid selection. Range of 1..3 expected.");

       return;         
     } 

     // n is valid
     switch (n) {
       case 1:
         Console.WriteLine("Current value is {0}", 1);
         break;
       case 2:
         Console.WriteLine("Current value is {0}", 2);
         break;
       case 3:
         Console.WriteLine("Current value is {0}", 3);
         break;
     }
   }

现在我们准备继续运行例程( repeat 通常是一个 loop ;这里有do..while):

   static void Main() {
     do {
       MyRoutine();

       Console.WriteLine("Would you like to repeat? Y/N");
     }
     while (char.ToUpper(Console.ReadKey().KeyChar) == 'y');

     Console.WriteLine("Press any key to exit.");
     Console.ReadKey();
   }  

答案 2 :(得分:0)

谢谢大家。 我设法使答案都成功了。这是这段代码现在的样子,实际上可以按照我想要的方式工作。

using System;

class Switch
{
static void Main()
{
bool repeat;
char input ;
do {
    Console.Write("Enter your selection (1, 2, or 3): ");
    string s = Console.ReadLine();
    int n = Int32.Parse(s);

    switch (n)
    {
        case 1:
            Console.WriteLine("Current value is {0}", 1);
            break;
        case 2:
            Console.WriteLine("Current value is {0}", 2);
            break;
        case 3:
            Console.WriteLine("Current value is {0}", 3);
            break;
        default:
            Console.WriteLine("Sorry, invalid selection.");
            break;
    }

Console.WriteLine("Would you like to repeat? Y/N");
input = Convert.ToChar(Console.ReadLine());

    }
  while (input == 'y');

 Console.WriteLine("Press any key to exit.");
 Console.ReadKey();

}  


}

答案 3 :(得分:-1)

这里有个很好的循环技巧。 对于初学者,如果您不希望该应用杀死自己并保持打开状态进入2018年-让我们成为HostBuilder!

您可以启动和保持应用程序的运行状态,并保持异步,双赢,因此,作为一个快速示例,这是我最近的事件引擎的主要切入点:

public static async Task Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        var startup = new Startup();

        var hostBuilder = new HostBuilder()
            .ConfigureHostConfiguration(startup.ConfigureHostConfiguration)
            .ConfigureAppConfiguration(startup.ConfigureAppConfiguration)
            .ConfigureLogging(startup.ConfigureLogging)
            .ConfigureServices(startup.ConfigureServices)
            .Build();

        await hostBuilder.RunAsync();
    }

向Microsoft.Extensions.Hosting添加nuget包引用。

如果您现在可以解决DI,则可以跳过所有的启动...行。 另外,您还需要将此行添加到您的项目文件中:

<LangVersion>latest</LangVersion>

应用程序运行后,将自动运行IHostedService的任何实现。 我将控制台代码放在这里,所以这是我的示例:

using MassTransit;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Trabalhos.EventsEngine.Messages;

namespace Trabalhos.EventsEngine.ClientExample
{
    public class SenderHostedService : IHostedService
    {
        private readonly IBusControl eventsEngine;
        private readonly ILogger<SenderHostedService> logger;

        public SenderHostedService(IBusControl eventsEngine, ILogger<SenderHostedService> logger)
        {
            this.eventsEngine = eventsEngine;
            this.logger = logger;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var products = new List<(string name, decimal price)>();

            Console.WriteLine("Welcome to the Shop");
            Console.WriteLine("Press Q key to exit");
            Console.WriteLine("Press [0..9] key to order some products");
            Console.WriteLine(string.Join(Environment.NewLine, Products.Select((x, i) => $"[{i}]: {x.name} @ {x.price:C}")));
            for (;;)
            {
                var consoleKeyInfo = Console.ReadKey(true);
                if (consoleKeyInfo.Key == ConsoleKey.Q)
                {
                    break;
                }

                if (char.IsNumber(consoleKeyInfo.KeyChar))
                {
                    var product = Products[(int)char.GetNumericValue(consoleKeyInfo.KeyChar)];
                    products.Add(product);
                    Console.WriteLine($"Added {product.name}");
                }

                if (consoleKeyInfo.Key == ConsoleKey.Enter)
                {
                    await eventsEngine.Publish<IDummyRequest>(new
                    {
                        requestedData = products.Select(x => new { Name = x.name, Price = x.price }).ToList()
                    });

                    Console.WriteLine("Submitted Order");

                    products.Clear();
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private static readonly IReadOnlyList<(string name, decimal price)> Products = new List<(string, decimal)>
        {
            ("Bread", 1.20m),
            ("Milk", 0.50m),
            ("Rice", 1m),
            ("Buttons", 0.9m),
            ("Pasta", 0.9m),
            ("Cereals", 1.6m),
            ("Chocolate", 2m),
            ("Noodles", 1m),
            ("Pie", 1m),
            ("Sandwich", 1m),
        };
    }
}

这将配置,运行并保持运行状态。 这里最酷的事情也是for(;;)循环,这是一个巧妙的技巧,可以使其在循环中运行,因此您可以一遍又一遍地重新进行操作,托管事情仅意味着您无需担心使控制台保持活动状态。

我什至拥有您想要的转义键:

if (consoleKeyInfo.Key == ConsoleKey.Q)
            {
                break;
            }

有关使用托管设置的深入示例,请使用此链接https://jmezach.github.io/2017/10/29/having-fun-with-the-.net-core-generic-host/

仔细阅读所有内容,对您有帮助。