APP重启后JSON文件内提醒数据无法加载,求排查代码问题
问题排查与修复方案
1. 未初始化reminders集合
你的代码里没显示reminders字段的定义,如果它没提前初始化,加载文件前reminders会是null——哪怕保存时能正常写入,加载时也可能因为集合状态异常导致数据无法正常绑定,甚至触发空引用错误。
修复:在类里显式初始化集合:
private List<Tuple<DateTime, string>> reminders = new List<Tuple<DateTime, string>>();
2. jsonFilePath未正确定义
代码里用了jsonFilePath但没给出具体路径值,如果路径错误(比如相对路径指向了非预期目录,或未设置有效绝对路径),会导致加载时找不到之前保存的文件。
修复:明确指定文件路径,比如保存到程序运行目录:
// 需添加 using System.IO; 和 using System; 引用 private string jsonFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "reminders.json");
3. 加载时Note控件内容赋值错误
保存时你把note.title.Text + "\n" + note.body.Text存入了Tuple.Item2,但加载时却把同一个reminder.Item2同时赋值给标题和内容,这会导致内容重复,且无法区分原始的标题与正文。
优化修复:放弃Tuple,改用自定义类存储数据,序列化/反序列化逻辑更清晰:
// 自定义Reminder类 public class Reminder { public DateTime CreatedTime { get; set; } public string Title { get; set; } public string Body { get; set; } } // 替换原reminders字段 private List<Reminder> reminders = new List<Reminder>(); // 添加Note时修改保存逻辑 reminders.Add(new Reminder { CreatedTime = DateTime.Now, Title = note.title.Text, Body = note.body.Text }); // 加载时修改赋值逻辑 foreach (var reminder in reminders) { Note note = new Note(); note.title.Text = reminder.Title; note.body.Text = reminder.Body; note.Location = nextNoteLocation; notesPanel.Controls.Add(note); nextNoteLocation.Y += note.Height + 10; }
4. 调试建议
- 检查
jsonFilePath对应目录下是否存在reminders.json,确认文件内容是否符合预期格式。 - 在
LoadRemindersFromJsonFile方法里加断点,查看反序列化后的reminders是否有数据。 - 确认
notesPanel的AutoScroll属性设为true,避免加载的Note控件超出可视范围,造成“未加载”的假象。
内容的提问来源于stack exchange,提问作者mizuuno
相关产品推荐
相关产品推荐

