C#TryParse

1 c# 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';
}
Run Code Online (Sandbox Code Playgroud)

我想这样做它不会退出,除非char是'g'或'c'帮助!:)

ant*_*ijn 5

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];
Run Code Online (Sandbox Code Playgroud)


Dre*_*kes 5

您是否使用Console.ReadLine,用户必须Enter在按c或后按g.请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;
    }
}
Run Code Online (Sandbox Code Playgroud)