c# - 如何保存和引用用户输入 c#(ToDo 控制台应用程序)
问题描述
我是 C# 新手,作为我的第一个“程序”,我想构建一个在控制台中运行的 ToDo 列表应用程序。
我已经制定了程序的基本框架,但我似乎没有找到如何在主代码之外保存用户数据,以便在下一个会话中再次引用它。
我不想暂时将任务保存为变量。
我的应用程序如何工作的想法是,如果我打开程序并且我可以选择编写/添加任务或读取任务。
如果我编写一个新任务,除了我在过去会话中添加的任务之外,控制台应该显示更新后的 ToDo 列表以及最新任务。
现在我不打算添加“删除任务”按钮,也许在我了解如何解决第一个问题之后。如果相关,我正在使用 VisualStudio for mac。
解决方案
有很多方法可以做到这一点。
最简单和最常用的一种是 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"
}
]
推荐阅读
- database - 尝试在 Flutter 中打开数据库时对“this”表达式的引用无效
- r - 试图遍历一个列表来做重复的突变
- postgresql - 将 postgresql 连接到其他硬盘上的数据库
- arrays - 试图让我的对象中的对象将它们的 id 用于我的 useState
- java - 在 Thymeleaf 表中显示多行
- linux - 为什么在 Debian 中有不同的方法来重启 apache2 和网络?
- python - 如何检索镶木地板文件中 TIMESTAMP 列的 idAdjustedUTC 标志值?
- node.js - (Node.js) 如何将转换后的 .JSON 文件保存在全局变量中?
- r - 在两组向量上进行 for 循环的 purrr 解决方案
- swift - 如何在整数的 UIPicker 视图中添加特殊字符