温馨提示×

c# readline怎样实现输入历史记录功能

c#
小樊
82
2024-06-24 11:09:30
栏目: 编程语言

要实现输入历史记录功能,可以通过保存用户输入的历史记录并在用户按键盘向上或向下箭头键时显示相应的历史记录。以下是一个简单的示例代码:

using System;
using System.Collections.Generic;

class Program
{
    static List<string> history = new List<string>();
    static int currentIndex = -1;

    static void Main()
    {
        string input;

        do
        {
            Console.Write("Enter a command: ");
            input = ReadLineWithHistory();

            if (!string.IsNullOrEmpty(input))
            {
                history.Add(input);

                // 处理用户输入的命令

            }

        } while (input != "exit");
    }

    static string ReadLineWithHistory()
    {
        ConsoleKeyInfo key;
        string input = "";
        
        do
        {
            key = Console.ReadKey(true);

            if (key.Key == ConsoleKey.Backspace)
            {
                if (input.Length > 0)
                {
                    input = input.Remove(input.Length - 1);
                    Console.Write("\b \b");
                }
            }
            else if (key.Key == ConsoleKey.Enter)
            {
                Console.WriteLine();
                return input;
            }
            else if (key.Key == ConsoleKey.UpArrow)
            {
                currentIndex = Math.Max(0, currentIndex - 1);
                if (currentIndex >= 0 && currentIndex < history.Count)
                {
                    input = history[currentIndex];
                    Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
                    Console.Write(input);
                }
            }
            else if (key.Key == ConsoleKey.DownArrow)
            {
                currentIndex = Math.Min(history.Count - 1, currentIndex + 1);
                if (currentIndex >= 0 && currentIndex < history.Count)
                {
                    input = history[currentIndex];
                    Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
                    Console.Write(input);
                }
            }
            else
            {
                input += key.KeyChar;
                Console.Write(key.KeyChar);
            }

        } while (true);
    }
}

在这个示例代码中,我们通过使用ConsoleKey.UpArrowConsoleKey.DownArrow来实现向上和向下箭头键浏览历史记录,同时也实现了Backspace键删除字符的功能。历史记录保存在history列表中,currentIndex用于记录当前浏览到的历史记录的索引。当用户按Enter键时,返回输入的命令。

请注意,这只是一个简单的实现,您可能需要根据自己的需求进行修改和扩展。

0