自制 Console 控制器,簡化 Console 程式的命令判斷

  • 86
  • 0

自制 Console 控制器,簡化 Console 程式的命令判斷



    class Program
    {
        static void Main(string[] args)
        {
            var con = new Shell();
            con["exit"] = con.Exit;
            con["quit"] = con.Exit;
            con["cls"] = () => Console.Clear();
            con["now"] = () => Console.WriteLine(DateTime.Now);
            con["date"] = () => Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd"));
            con["time"] = () => Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff"));
            con["dir"] = () => System.IO.Directory.GetFiles(".").ToList().ForEach(o => Console.WriteLine(o));
            con.Otherwise = input => Console.WriteLine("Invalid command");
            con.Start();
        }
    }
    public class Shell
    {
        bool _keepRunning;
        public Dictionary<string, Action> Commands { get; private set; }
        public Action<string> Otherwise { get; set; }
        public Action this[string command]
        {
            get { return Commands[command]; }
            set { Commands[command] = value; }
        }
        public Shell()
        {
            Commands = new Dictionary<string, Action>();
        }
        public void Exit()
        {
            _keepRunning = false;
        }
        public void Start()
        {
            _keepRunning = true;
            while (_keepRunning)
            {
                var cmd = Console.ReadLine();
                if (string.IsNullOrEmpty(cmd)) continue;
                Action action;
                if (Commands.TryGetValue(cmd, out action))
                    action?.Invoke();
                else
                    Otherwise?.Invoke(cmd);
            }
        }
    }