您可能想使用字典:
private Dictionary<string, string> _answers = new Dictionary<string, string>();
public void StudentDetailInput()
{
string[] takeinput = new string[] {
"FirstName",
"Surname",
"MiddleName",
"StudentId",
"Subject",
"AddressLine1",
"AddressLine2",
"Town",
"Postcode",
"Telephone",
"Email"
};
_answers.Clear();
for (int x = 0; x < takeinput.Length; x++)
{
Console.Write(takeinput[x] + ": ");
var answer = Console.ReadLine();
_answers.Add(takeinput[x], answer);
}
}
所以你可以像这样显示答案:
for(var i = 0; i < _answers.Count; i++)
{
Console.WriteLine("{0}: {1}", _answers.Keys[i], _answers.Values[i]);
}
如果您担心您不想在控制台上使用这么多行,您可以跟踪答案的长度并尝试将光标放在到目前为止的答案后面。这样做的问题是您需要考虑屏幕的宽度(可以由用户调整)来计算正确的行和位置。
这种结构的另一个问题是用户会期望光标向下移动一行(这就是 enter 所做的),因此用户体验可能会受到影响。
另一种方法是在每次输入后清除屏幕,从控制台的第 2 行开始显示到目前为止的所有答案,并将下一个问题放在第 1 行:
for (int x = 0; x < takeinput.Length; x++)
{
Console.Clear();
for(y = 0; y < x; y++)
{
Console.SetCursorPosition(0, y + 1);
Console.WriteLine("{0}: {1}", _answers.Keys[y], _answers.Values[y]);
}
Console.SetCursorPosition(0, 0);
Console.Write(takeinput[x] + ": ");
var answer = Console.ReadLine();
_answers.Add(takeinput[x], answer);
}
当问题的数量多于控制台上的行数时,这可能会出错。