加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在应用程序设置中保存对象集合

发布时间:2020-12-15 04:27:19 所属栏目:百科 来源:网络整理
导读:我试图在应用程序设置中存储自定义对象的集合. 从this related question的一些帮助,这里是我目前拥有的: // implementing ApplicationSettingsBase so this shows up in the Settings designer's // browse functionpublic class PeopleHolder : Applicatio
我试图在应用程序设置中存储自定义对象的集合.

从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类型的属性,并将范围设置为“User”. Save()方法似乎成功完成,没有错误消息,但每次重新启动应用程序设置都不会保留.

虽然在上面的代码中没有显示,我可以坚持Strings,只是不是我的自定义集合(我注意到在其他类似的问题,有时可能有版本号的问题,这阻止了在调试时保存设置,所以我想规则作为可能的罪魁祸首.)

有任何想法吗?我确定有一个非常简单的方法来做到这一点,我只是想念:).

谢谢你的帮助!

解决方法

我想出了 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 = "bill" }
        };
        Properties.Settings.Default.Save();
    }
    else
    {
        MessageBox.Show(Properties.Settings.Default.AllPeople.People.Count.ToString());
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读