0

I've just started understanding C# code and wanted to try out a Console Application. Fairly basic, and would involve a loop to carry out some work until the user decides to quit. This is how my program looks for now.

public void Method1(string[] args)
{
    if (args.Length != 0)
    {
        DoWork(args);
        ResetValues();
        Loop(parameter);                
    }
    else
    {
        Console.WriteLine("No arguments passed");
        string helpMsg ...
        Console.WriteLine(helpMsg);
    }

public void Loop(parameter)
{
    bool wantsContinue = true;

    while (wantsContinue)
    {
        Console.WriteLine("What would you like to do now?\n-Exit\tWrite 'e'\n-Run again\tWrite 'r'");
        ConsoleKeyInfo command = Console.ReadKey();
        char key = command.KeyChar;

        switch (key)
        {
            case 'e':
                return;
            case 'r':
                Console.WriteLine("Please enter your commands");                        
                string input = Console.ReadLine();
                Method1(parameters);
                break;
            case 'h':
                Console.WriteLine(helpMsg);
                break;
            default:
                Console.WriteLine("\nInvalid argument. Enter again");
                break;
        }
    }
}

public void MethodContinuous(input)
{
    Console.WriteLine(input);
    string[] args = input.Split(' ');

    if (args.Length != 0)
    {
        DoWork(args);
    }
    else
    {
        Console.WriteLine("No arguments passed");
        string helpMsg = ...
        Console.WriteLine(helpMsg);
    }
}

However, I am getting a problem which I can't figure out. When the program enters the loop first time, it sets the parameters correctly, but when the loop is continuing, it gives me the user input from the previous run. I'm probably doing something that isn't right, or the Console works a bit differently. Can the expert figure it out?

4

2 回答 2

1

break在每个case-Statement之后设置一个

switch (key)
    {
        case 'e':
            wantsContinue = false;
            break;
        case 'r':
            Console.WriteLine("\nYippeeee! I get to run again");
            Console.WriteLine("Please enter your commands");                        
            string input = Console.ReadLine();
            Method1(parameters);
            break;
        case 'h':
            Console.WriteLine(helpMsg);
            break;
        default:
            Console.WriteLine("\nInvalid argument. Enter again");
            break;
    }

来自MSDN

所选部分中的语句列表的执行从第一条语句开始,并通过语句列表继续执行,通常直到到达跳转语句,例如 break、goto case、return 或 throw。此时,控制转移到 switch 语句之外或转移到另一个 case 标签。

于 2013-05-13T12:54:53.360 回答
0

尝试这个

case 'r':
            Console.WriteLine("Please enter your commands");                        
            parameters[0]= Console.ReadLine();
            Method1(parameters);
            break;
于 2013-05-13T13:27:10.147 回答