【问题标题】:C# While TryParseC# 虽然 TryParse
【发布时间】:2013-03-17 20:14:07
【问题描述】:
char typeClient = ' ';
bool clientValide = false;
while (!clientValide)
{
     Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
     clientValide = char.TryParse(Console.ReadLine(), out typeClient);
     if (clientValide)
         typeClient = 'c';
}

我想让它不会退出 while 除非 char 是 'g' 或 'c' 帮助 ! :)

【问题讨论】:

  • 看起来像是在尝试做很多事情。只需根据字符串 "c""g" 验证传入的字符串(如果您想要不区分大小写,请使用 ToLower()

标签: c# tryparse


【解决方案1】:
string input;
do {
    Console.WriteLine("Entrez le type d'employé (c ou g):");
    input = Console.ReadLine();
} while (input != "c" && input != "g");

char typeClient = input[0];

【讨论】:

    【解决方案2】:

    你是否使用Console.ReadLine,用户必须在按cg后按Enter。请改用ReadKey,以便即时响应:

    bool valid = false;
    while (!valid)
    {
        Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
        var key = Console.ReadKey();
        switch (char.ToLower(key.KeyChar))
        {
            case 'c':
                // your processing
                valid = true;
                break;
            case 'g':
                // your processing
                valid = true;
                break;
            default:
                Console.WriteLine("Invalid. Please try again.");
                break;
        }
    }
    

    【讨论】:

      【解决方案3】:

      你真的很亲密,我认为这样的事情对你很有效:

      char typeClient = ' ';
      while (typeClient != 'c' && typeClient != 'g')
      {
          Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
          var line = Console.ReadLine();
          if (!string.IsNullOrEmpty(line)) { typeClient = line[0]; }
          else { typeClient = ' '; }
      }
      

      基本上,当用户输入内容时,它会将输入读入typeClient 变量,因此循环将继续,直到他们输入gc

      【讨论】:

      • 那不会编译。 ReadLine 返回 string,而不是 char
      • 如果用户输入gblahblah会怎样?
      • @DrewNoakes:是的,谢谢,我已经修改了代码。而且我现在没有坐在 Visual Studio 前面 - 只是想帮助 OP 了解这个想法。
      • 编辑后会更好,但如果用户在没有任何其他字符的情况下按回车,[0] 将抛出一个IndexOutOfBoundsException
      • @bas 现在他有 +26 reps(+3 -2) 这个丑陋的答案。 (顺便说一句,我还没有投反对票。但是。)
      【解决方案4】:

      您可以将ConsoleKeyInfoConsole.ReadKey() 一起使用:

       ConsoleKeyInfo keyInfo;
       do {
         Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
         keyInfo = Console.ReadKey();
       } while (keyInfo.Key != ConsoleKey.C && keyInfo.Key != ConsoleKey.G);
         
      

      【讨论】:

      • 请仅提供英文版。
      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2012-03-01
      • 2012-10-06
      相关资源
      最近更新 更多