C#switch语句验证

时间:2013-07-27 03:47:23

标签: c# validation switch-statement

我想知道在C#中是否有办法做这样的事情:

some loop here
{
    Console.WriteLine("Please enter a or b");
    switch (Console.ReadLine().ToLower())
    {
        case "a":
            //some code here
            break;
        case "b":
            //some code here
            break;
        default:
            Console.WriteLine("Error, enter a or b");
            repeat loop
    }
}

这可能是一个愚蠢的问题,但这样的事情对我的任务非常有益。

2 个答案:

答案 0 :(得分:3)

为什么不呢。运行仅在输入a或b时存在的while循环。

bool condition = false;

Console.WriteLine("Please enter a or b");
string str = string.Empty;
while (!condition)
{
     str = Console.ReadLine().ToLower();
     switch (str)
     {
         case "a":
             //some code here
             condition = true;
             break;
         case "b":
             //some code here
             condition = true;
             break;
         default:
             Console.WriteLine("Error, enter a or b");
             break;
     }
 }
 Console.WriteLine("You have entered {0} ", str);
 Console.ReadLine();

答案 1 :(得分:1)

这样的事情怎么样?

var acceptedValues = new List<string>()
{
    "a",
    "b",
};

Console.WriteLine("Please enter {0}", string.Join("or", acceptedValues));
var enteredValue = string.Empty;
do
{
    enteredValue = Console.ReadLine().ToLower();
} while (!acceptedValues.Contains(enteredValue));