如何在 .net 控制台应用程序中设置默认输入值?
这是一些虚构的代码:
Console.Write("Enter weekly cost: ");
string input = Console.ReadLine("135"); // 135 is the default. The user can change or press enter to accept
decimal weeklyCost = decimal.Parse(input);
当然,我不希望事情这么简单。我打赌必须做一些低级的、不受管理的事情;我只是不知道怎么办。
EDIT
我知道我可以用默认值替换无输入。我要问的不是这个。我正在尝试了解实现我所描述的行为所涉及的内容:为用户提供可编辑的默认值。我也不担心输入验证;我的问题与此无关。
我相信您将通过监听每个按键来手动管理此操作:
快速拼凑在一起的例子:
// write the initial buffer
char[] buffer = "Initial text".ToCharArray();
Console.WriteLine(buffer);
// ensure the cursor starts off on the line of the text by moving it up one line
Console.SetCursorPosition(Console.CursorLeft + buffer.Length, Console.CursorTop - 1);
// process the key presses in a loop until the user presses enter
// (this might need to be a bit more sophisticated - what about escape?)
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
switch (keyInfo.Key)
{
case ConsoleKey.LeftArrow:
...
// process the left key by moving the cursor position
// need to keep track of the position in the buffer
// if the user presses another key then update the text in our buffer
// and draw the character on the screen
// there are lots of cases that would need to be processed (backspace, delete etc)
}
keyInfo = Console.ReadKey(true);
}
这非常复杂 - 您必须确保光标不会超出范围并手动更新缓冲区。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)