gpt4 book ai didi

c# - 在应用程序设置中保存对象集合时遇到问题

转载 作者:太空狗 更新时间:2023-10-29 17:43:44 25 4
gpt4 key购买 nike

我正在尝试在应用程序设置中存储自定义对象的集合。

this related question 的帮助下,这是我目前拥有的:

// implementing ApplicationSettingsBase so this shows up in the Settings designer's 
// browse function
public class PeopleHolder : ApplicationSettingsBase
{
[UserScopedSetting()]
[SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]
public ObservableCollection<Person> People { get; set; }
}


[Serializable]
public class Person
{
public String FirstName { get; set; }
}

public MainWindow()
{
InitializeComponent();

// AllPeople is always null, not persisting
if (Properties.Settings.Default.AllPeople == null)
{
Properties.Settings.Default.AllPeople = new PeopleHolder()
{
People = new ObservableCollection<Person>
{
new Person() { FirstName = "bob" },
new Person() { FirstName = "sue" },
new Person() { FirstName = "bill" }
}
};
Properties.Settings.Default.Save();
}
else
{
MessageBox.Show(Properties.Settings.Default.AllPeople.People.Count.ToString());
}
}

在 Settings.Settings Designer 中,我通过浏览器按钮添加了 PeopleHolder 类型的属性,并将范围设置为“用户”。 Save() 方法似乎成功完成,没有错误消息,但每次我重新启动应用程序设置时都不会保留。

虽然上面的代码中没有显示,但我能够保留字符串,而不是我的自定义集合(我在其他类似问题中注意到 SO 有时版本号会出现问题,这会阻止在调试时保存设置,所以我想排除这可能是罪魁祸首。)

有什么想法吗?我确信有一个非常简单的方法可以做到这一点,我只是想念它:)。

感谢您的帮助!

最佳答案

感谢 this question,我弄明白了!

正如该问题中所建议的,我将其添加到 Settings.Designer.cs 中:

    [global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public ObservableCollection<Person> AllPeople
{
get
{
return ((ObservableCollection<Person>)(this["AllPeople"]));
}
set
{
this["AllPeople"] = value;
}
}

然后我只需要以下代码:

[Serializable]
public class Person
{
public String FirstName { get; set; }
}

public MainWindow()
{
InitializeComponent();

// this now works!!
if (Properties.Settings.Default.AllPeople == null)
{
Properties.Settings.Default.AllPeople = new ObservableCollection<Person>
{
new Person() { FirstName = "bob" },
new Person() { FirstName = "sue" },
new Person() { FirstName = "bill" }
};
Properties.Settings.Default.Save();
}
else
{
MessageBox.Show(Properties.Settings.Default.AllPeople.People.Count.ToString());
}
}

关于c# - 在应用程序设置中保存对象集合时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7681957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com