c# - (已关闭)C# 控制台自动完成/建议输入,代码改进
问题描述
我目前正在编写一个 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;
解决方案
-
if (Keywords.Length == 0) throw new Exception("No Keywords set!");
而是使用
if (Keywords.Length == 0) throw new ArgumentException(nameof(Keywords), "No Keywords set!");
我不会
System
用作变量名。System
是一个非常常见的命名空间。不确定是不是因为格式化,但是分配之间的标签不一致,使代码更难阅读
您计算要清除的长度,但从不使用它// 设置长度清零,如果suggestions == "",系统字符串长度需要清零 toClear = (System.Length>suggestion.Length) ? System.Length : 建议.Length;
推荐阅读
- c# - 无法与“Stockfish-9-armv7”二进制文件通信
- javascript - 如何让我的 JavaScript 代码更干?
- c++ - C++向量擦除函数说明
- java - CrystalClear 报告错误 [219] [池管理器] 无法加载指定的驱动程序:null null
- jsp - 错误 404:资源(.jsp 文件)不可用
- r - R Likert Package:增加分面条标签文本大小
- java - AESWrap 和 to-wrap-key 长度长度/填充问题
- plot - 如何以八度音阶绘制 3D
- node.js - 休息API节点js
- latex - bookdown 中的新乳胶环境未在 html 中正确显示