【发布时间】:2021-12-17 23:54:04
【问题描述】:
我正在尝试构建一个更高级的 ToDoList-Console 程序。我正在学习序列化,但我似乎不明白如何:
- 实现 2 种任务
- 将它们保存在文件中(不必是 json)
- 在考虑任务类型的同时读取文件
我的目标是拥有 2 种方法:task1 和 task2。 Task1 是主要任务,task2 是任务的子任务,可以在控制台中使用 \t 进行可视化。 这是我当前的代码,它只是将任务保存为字符串,没有任何复杂性。
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);
}
// Loading list
{
string json = File.ReadAllText(_saveFileName);
List<TodoItem> items = JsonSerializer.Deserialize<List<TodoItem>>(json);
// Loading items
foreach (var todo in items)
Console.WriteLine(todo);
}
}```
【问题讨论】:
标签: c# serialization