首页 > 解决方案 > 如何保存和引用用户输入 c#(ToDo 控制台应用程序)

问题描述

我是 C# 新手,作为我的第一个“程序”,我想构建一个在控制台中运行的 ToDo 列表应用程序。

我已经制定了程序的基本框架,但我似乎没有找到如何在主代码之外保存用户数据,以便在下一个会话中再次引用它。

我不想暂时将任务保存为变量。

我的应用程序如何工作的想法是,如果我打开程序并且我可以选择编写/添加任务或读取任务。

如果我编写一个新任务,除了我在过去会话中添加的任务之外,控制台应该显示更新后的 ToDo 列表以及最新任务。

现在我不打算添加“删除任务”按钮,也许在我了解如何解决第一个问题之后。如果相关,我正在使用 VisualStudio for mac。

标签: c#

解决方案


有很多方法可以做到这一点。

最简单和最常用的一种是 JSON。

这是我编写的完整程序,您可以进行试验。

public class TodoItem
{
    public string Description { get; set; }
    public DateTime? DueOn { get; set; }

    public override string ToString()
    {
        return $"{this.Description}";
    }
}

internal static class Program
{
    static private readonly string _saveFileName = "todo.json";
    static void Main()
    {
        {
            // An example list containing 2 items
            List<TodoItem> items = new List<TodoItem> {
                new TodoItem { Description = "Feed the dog" },
                new TodoItem { Description = "Buy groceries", DueOn = new DateTime(2021, 9, 30, 16, 0, 0) }
            };
            // Serialize it to JSON
            string json = JsonSerializer.Serialize(items, new JsonSerializerOptions() { WriteIndented = true });

            // Save it to a file
            File.WriteAllText(_saveFileName, json);
        }

        // Now we'll load the list back from the file
        {
            string json = File.ReadAllText(_saveFileName);

            List<TodoItem> items = JsonSerializer.Deserialize<List<TodoItem>>(json);

            // Check whether the list has loaded correctly
            foreach (var todo in items)
                Console.WriteLine(todo);
        }

    }

程序输出:

喂狗
买杂货


todo.json文件内容:

[
  {
    "Description": "Feed the dog",
    "DueOn": null
  },
  {
    "Description": "Buy groceries",
    "DueOn": "2021-09-30T16:00:00"
  }
]

推荐阅读