【问题标题】:Running the function again on C#在 C# 上再次运行该函数
【发布时间】:2019-04-05 15:30:53
【问题描述】:

我有这个带开关的简单代码。 问题是,在任何情况下完成或默认后,代码都会终止。 我想在完成后得到什么,它会问“你想重复一次”这个问题,如果答案是 Y,它将再次运行 Main,它是 N,它将终止,依此类推。 我尝试了 do...while 并且没有任何其他建议?

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

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();
    }
}

.

【问题讨论】:

标签: c# class switch-statement repeat


【解决方案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 循环并在末尾检查。

【讨论】:

  • 这个不工作。选择选项后终止程序。不管你选择哪一个。
  • 您可能需要将repeat = (input == 'Y') 更改为repeat = (input == 'Y' || 'y')
  • 我照你说的做了。这就是我得到的。它只是显示问题。并立即终止程序。没有选择选项。 (输入您的选择(1、2 或 3):1 当前值为 1 您想重复吗?Y/N 按任意键退出。)
  • 尝试将input = Console.ReadKey().KeyChar; repeat = (input == 'Y'); 更改为input = Console.ReadLine(); repeat = (input.ToUpper() == "Y") 您现在需要在输入Y 后按回车
【解决方案2】:

这是一个循环的好技巧。 对于初学者,如果您不希望应用程序自我毁灭并保持打开状态以进入 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();
    }

将 nuget 包引用添加到 Microsoft.Extensions.Hosting。

如果你现在有 DI 需要整理,你可以跳过所有的 startup... 行。 您还需要将此行添加到您的项目文件中:

<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/

浏览一遍应该会有所帮助。

【讨论】:

    【解决方案3】:

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

       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 通常是一个循环;这里有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();
       }  
    

    【讨论】:

    • 这个也不适合我。选择重复选项后,它会终止。 “输入您的选择(1、2 或 3):3 当前值为 3 您要重复吗?是/否按任意键退出。”
    • @Robertas:你可能按小写的y,而不是Y;让我们接受char.ToUpper 的这两种可能性 - 请查看我的编辑
    • 它甚至没有让我选择这样做。我设法做到了。我更新了我的代码。
    【解决方案4】:

    谢谢大家。 我设法同时回答了两个问题并取得了成功。这就是这段代码现在的样子,它实际上是按照我想要的方式工作的。

    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();
    
    }  
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多