简体   繁体   English

C# While TryParse

[英]C# While TryParse

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';
}

I'd like to make it so it doesn't exit the while unless the char is 'g' or 'c' help !我想让它不会退出 while 除非字符是 'g' 或 'c' 帮助! :) :)

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];

Is you use Console.ReadLine , the user has to press Enter after pressing c or g .您是否使用Console.ReadLine ,用户必须在按cg后按Enter Use ReadKey instead so that the response is instantaneous:改用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;
    }
}

You're really close, I think something like this will work well for you:你真的很接近,我认为这样的事情对你来说很有效:

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 = ' '; }
}

basically it reads the input into the typeClient variable when the user enters something so the loop will continue until they enter g or c .基本上,当用户输入某些内容时,它会将输入读入typeClient变量,因此循环将继续,直到他们输入gc

You can use ConsoleKeyInfo with Console.ReadKey() :您可以将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);
   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM