如何使用ApplicationSettingsBase将自定义类保存到用户设置?

时间:2012-06-16 13:40:29

标签: c# settings applicationsettingsbase

我正在尝试将自定义类保存到用户设置但没有取得多大成功。

我在Visual Studio 2010中使用Target framework =“.NET Framework 4”创建了一个测试项目。主窗体有两个文本框,用于显示和编辑普通测试字符串以及我的自定义类中的“标题”字段;连同两个按钮加载和保存设置。

最后,我添加了两个设置“TestString”(一个普通的字符串值)和TestData(MyDataClass的类型 - 我在项目的Properties.Settings选项卡中通过从Type下拉列表中选择“Browse ...”然后手动执行此操作在“选定类型”框中输入“MyUserSettingsTest.MyDataClass”,因为它最初没有出现在可用的类型列表中,但后来又出现了。)

在启动应用程序并单击LoadSettings时,事件处理程序会加载纯字符串和MyData,如果失败,则会创建MyDataClass的新实例。然后,我可以在表单上编辑纯字符串并测试数据标题,然后单击SaveSettings。如果我然后重新编辑值,请再次单击“LoadSettings”,将按预期为两个值恢复上次保存的值。到目前为止一切都很好。

问题是退出应用程序并重新启动时,普通测试字符串恢复正常,但MyData对象不是!显然,代码是将MyData保存到内存中,但不是永久存储?

主要表格代码是:

using System;
using System.Windows.Forms;

namespace MyUserSettingsTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public MyDataClass MyData {get;set;}

        private void loadSettingsButton_Click(object sender, EventArgs e)
        {
            this.myTextBox.Text = Properties.Settings.Default.TestString;
            this.MyData = Properties.Settings.Default.TestData;

            if (this.MyData == null)
            {
                this.MyData = new MyDataClass() { ID = 1, Title = "Default New Title" };
            }

            this.myDataTitleTextBox.Text = this.MyData.Title;
        }

        private void saveSettingsButton_Click(object sender, EventArgs e)
        {
            this.MyData.Title = this.myDataTitleTextBox.Text;

            Properties.Settings.Default.TestString = this.myTextBox.Text;
            Properties.Settings.Default.TestData = this.MyData;
            Properties.Settings.Default.Save();
        }
    }
}

我的测试数据类代码是:

using System.Configuration;

namespace MyUserSettingsTest
{
    public class MyDataClass : ApplicationSettingsBase
    {
        public MyDataClass()
        {
        }

        private int _id;
        private string _title;

        [UserScopedSetting()]
        [SettingsSerializeAs(SettingsSerializeAs.Xml)] 
        public int ID
        {
            get { return _id; }
            set { _id = value; }
        }

        [UserScopedSetting()]
        [SettingsSerializeAs(SettingsSerializeAs.Xml)] 
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
    }
}

我不知道它是否有帮助但是自动生成的app.config文件(其中包含TestString但不是TestData !!的设置)是:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <section name="MyUserSettingsTest.Properties.Settings"     type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
        </sectionGroup>
    </configSections>
    <userSettings>
        <MyUserSettingsTest.Properties.Settings>
            <setting name="TestString" serializeAs="String">
                <value/>
            </setting>
        </MyUserSettingsTest.Properties.Settings>
    </userSettings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

自动生成的Settings.Designer.cs文件为:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.269
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MyUserSettingsTest.Properties {


[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {
            return defaultInstance;
        }
    }

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("")]
    public string TestString {
        get {
            return ((string)(this["TestString"]));
        }
        set {
            this["TestString"] = value;
        }
    }

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public global::MyUserSettingsTest.MyDataClass TestData {
        get {
            return ((global::MyUserSettingsTest.MyDataClass)(this["TestData"]));
        }
        set {
            this["TestData"] = value;
        }
    }
}
}

任何人都可以告诉我我做错了什么,或者需要做些什么才能使我的自定义类能够正确地保持用户设置。

1 个答案:

答案 0 :(得分:1)

将自定义对象另存为序列化字符串。然后你只需要存储一个字符串。例如,使用Json .NET JsonConverter序列化和反序列化对象。

Properties.Settings.Default.TestData = JsonConvert.SerializeObject<MyDataClass>(this.MyData);

然后你可以像这样读回来

this.MyData = JsonConvert.DeserializeObject<MyDataClass>(Properties.Settings.Default.TestData);