【发布时间】:2018-08-13 13:41:53
【问题描述】:
我目前正在编写一个 C# 控制台应用程序。部分原因是用户需要输入一个相当复杂的系统名称。为了更容易,我编写了一个函数,它使用 string[] 关键字并自动完成用户输入的字符串 - 在运行时。
代码可以正常工作并按预期运行,但我很好奇如何改进代码(例如可用性、效率)。另外,缺少哪些功能,这是您所期望的?
感谢您的反馈!
if (Keywords.Length == 0)
throw new Exception("No Keywords set!");
bool searching = true; // true while looking for the keyword
Console.CursorVisible = true; // To help users understand where they are typing
string System = ""; // Initialization of output
string suggestion = Keywords[0]; // Initialization of default suggestion
int toClear = suggestion.Length; // Get the length of the line that needs to be cleared
while (searching)
{
Console.Write(new String(' ', toClear)); // Clear line
Console.CursorLeft = 0; // Relocate cursor to line start
Console.Write(System); // Write what has been written previously
if(suggestion != "") // If there is a suggestion fitting the entered string,
{ // complete the string in color and reset the cursor
int col = Console.CursorLeft;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write(suggestion.Substring(System.Length));
Console.ForegroundColor = ConsoleColor.White;
Console.CursorLeft = col;
}
string tempInput = Console.ReadKey().KeyChar.ToString();
if (tempInput.Equals("\r")) // Evaluate input:
{ // -> Enter
if (!suggestion.Equals("")) // Valid entry?
{
searching = false;
System = suggestion; // -> use suggestion
}
}
else if (tempInput.Equals("\b")) // Deleting last sign
{
if(System.Length>0)
System = System.Substring(0, System.Length - 1);
}
else // Any other sign is added to the string
System += tempInput;
// Set length to clear, if suggestion == "", the system string length needs to be cleared
toClear = (System.Length>suggestion.Length) ? System.Length : suggestion.Length;
// Reset suggestion. If no match is found, suggestion remains empty
suggestion = "";
// Check keywords for suggestion
for(int i= 0; i<Keywords.Length; i++)
{
if (Keywords[i].StartsWith(System))
{
suggestion = Keywords[i];
break;
}
}
}
// reset cursor visibility
Console.CursorVisible = false;
return System;
【问题讨论】:
-
将您拥有的(作为完整程序)发布到codereview.stackexchange.com。改进工作代码并不是 SO 的真正目的。
-
感谢@BrootsWaymb 我还不知道那个页面。我会把问题移到那里
-
此问题已移至Codereview.stackexchange.com。请在此处评论该主题。
-
我投票决定将此问题作为离题结束,因为该问题已移至 codereview。
-
@LasseVågsætherKarlsen 据我所知,我无法在问题中添加“[关闭]”标签,我无法删除它,因为有人回答了它并根据这个 post要走的路是接受我已经做过的答案。如果你能让我知道如何正式结束一个问题,我将不胜感激。
标签: c# user-interface input console usability