我当前正在编写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;
答案 0 :(得分:1)
Do not raise reserved exception types
if (Keywords.Length == 0)
throw new Exception("No Keywords set!");
代替使用
if (Keywords.Length == 0)
throw new ArgumentException(nameof(Keywords), "No Keywords set!");
我不会使用System
作为变量名。 System
是一个非常常见的命名空间。
不确定这是由于格式造成的,但是分配之间的选项卡不一致,并且使代码更难阅读
您计算要清除的长度,但从不使用
//设置要清除的长度,如果建议==“”,则需要清除系统字符串长度
toClear =(System.Length> suggestion.Length)? System.Length:建议。长度;