Console.Readline()之后的C#console Console.WriteLine()?

时间:2016-10-27 01:19:48

标签: c# console

我希望控制台输出基本上具有表单的一般外观。

以下是我希望输出显示的方式:

First Name:  //using Console.ReadLine() right here while there is other text below
Last Name:
Badge Number:

然后

First Name: Joe
Last Name: //using Console.ReadLine() right here while there is other text below
Badge Number:

最后

First name: Joe
Last name: Blow
Badge Number:  //using Console.ReadLine() right here

1 个答案:

答案 0 :(得分:9)

您需要Console.SetCursorPosition()方法。

IList<string> PromptUser(params IEnumerable<string> prompts)
{
    var results = new List<string>();
    int i = 0; //manual int w/ foreach instead of for(int i;...) allows IEnumerable instead of array
    foreach (string prompt in prompts)
    {
        Console.WriteLine(prompt);
        i++;
    }

    //do this after writing prompts, in case the window scrolled
    int y = Console.CursorTop - i; 

    if (y < 0) throw new Exception("Too many prompts to fit on the screen.");

    i = 0;
    foreach (string prompt in prompts)
    {
        Console.SetCursorPosition(prompt.Length + 1, y + i);
        results.Add(Console.ReadLine());
        i++;
    }
    return results;
}

看看all the things you can do with the Console

为了好玩,让我们更加可重复使用:

var inputs = PromptUser("First Name:", "Last Name:", "Badge Number:");

然后你会这样称呼它:

{{1}}