Properties.Settings.Default.myList添加项失败,触发NullReferenceException
解决Properties.Settings.Default.myList的NullReferenceException问题
看了你的代码,问题根源很清晰:你碰到的System.NullReferenceException是因为Properties.Settings.Default.myList初始状态是null,但你的Save方法里只判断了它为null就跳过,完全没做初始化操作,后面调用myList.Add(item)自然就会因为空引用报错。
修复方案
首先建议你把Settings里的myList类型设为System.Collections.Specialized.StringCollection——这是Settings默认支持的字符串集合类型,比普通List更适合持久化存储。然后修改Save方法,确保使用前先初始化集合:
private void Save() { // 若myList为空,先初始化一个新的StringCollection实例 if (Properties.Settings.Default.myList == null) { Properties.Settings.Default.myList = new System.Collections.Specialized.StringCollection(); } else { Properties.Settings.Default.myList.Clear(); } // 遍历ListBox项,转成字符串后添加到集合(避免类型不匹配) foreach (var item in listbox_items.Items) { Properties.Settings.Default.myList.Add(item.ToString()); } Properties.Settings.Default.Save(); }
额外优化建议
- 提前初始化:可以在程序启动时(比如窗体的
Load事件)提前完成myList的初始化,这样后续调用Save时就不用重复判断:
private void Form1_Load(object sender, EventArgs e) { if (Properties.Settings.Default.myList == null) { Properties.Settings.Default.myList = new System.Collections.Specialized.StringCollection(); } Restore(); // 启动时自动恢复之前保存的数据 }
- 确认Settings配置:右键项目→属性→设置,找到
myList,确认它的类型确实是System.Collections.Specialized.StringCollection,避免类型不兼容导致的隐性问题。
这样修改后,Save方法就不会再因为空引用抛出异常,ListBox里的项也能正确保存到Settings中了。
内容的提问来源于stack exchange,提问作者R00T
相关产品推荐
相关产品推荐

