简体   繁体   English

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

[英]How do I save a custom class to user settings using ApplicationSettingsBase?

I'm trying to save a custom class to user settings but not having much success. 我正在尝试将自定义类保存到用户设置但没有取得多大成功。

I've created a test project in Visual Studio 2010 with Target framework = ".NET Framework 4". 我在Visual Studio 2010中使用Target framework =“.NET Framework 4”创建了一个测试项目。 The main Form has two text boxes for displaying and editing a plain test string and the "Title" field from my custom class; 主窗体有两个文本框,用于显示和编辑普通测试字符串以及我的自定义类中的“标题”字段; together with two buttons to Load and Save the settings. 连同两个按钮加载和保存设置。

Finally, I added two settings "TestString" (a plain string value) and TestData (type of MyDataClass - I did this in the project's Properties.Settings tab by selecting "Browse..." from the Type dropdown list then manually entering "MyUserSettingsTest.MyDataClass" in the "Selected Type" box as it didn't originally appear in the available type list but then subsequently it does .) 最后,我添加了两个设置“TestString”(一个普通的字符串值)和TestData(MyDataClass的类型 - 我在项目的Properties.Settings选项卡中通过从Type下拉列表中选择“Browse ...”然后手动输入“MyUserSettingsTest”来完成此操作.MyDataClass“在”选定类型“框中,因为它最初没有显示在可用类型列表中,但随后它出现在。

On starting the application and clicking LoadSettings the event handler loads the plain string and MyData or, if this fails, creates a new instance of MyDataClass. 在启动应用程序并单击LoadSettings时,事件处理程序将加载纯字符串和MyData,如果失败,则会创建MyDataClass的新实例。 I can then edit the plain string and test data Title on the form and click SaveSettings. 然后,我可以在表单上编辑纯字符串并测试数据标题,然后单击SaveSettings。 If I then re-edit the values click LoadSettings again the last saved values are restored as expected for both values. 如果我然后重新编辑值,请再次单击“LoadSettings”,将按预期为两个值恢复上次保存的值。 So far so good. 到现在为止还挺好。

The problem is that on exiting the application and re-starting it the plain test string is restored ok but MyData object isn't! 问题是退出应用程序并重新启动它时,普通的测试字符串恢复正常,但MyData对象不是! Obviously, the code is persisting MyData to memory ok but not to the permanent store? 显然,代码是将MyData保存到内存中,但不是永久存储?

The main form code is: 主要表格代码是:

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();
        }
    }
}

My test data class code is: 我的测试数据类代码是:

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; }
        }
    }
}

I don't know if it's of help but the auto-generated app.config file (which contains the setting for TestString but NOT TestData!!?) is: 我不知道它是否有帮助,但是自动生成的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>

The auto-generated Settings.Designer.cs file is: 自动生成的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;
        }
    }
}
}

Please can anyone tell me what I'm doing wrong or what extra I need to do to get my custom class to persist to user settings properly. 请任何人都可以告诉我我做错了什么,或者需要做些什么才能使我的自定义类能够正确地保持用户设置。

Save your custom object as a serialized string. 将自定义对象保存为序列化字符串。 Then you only need to store a string. 然后你只需要存储一个字符串。 For example, use the Json .NET JsonConverter to serialize and deserialize objects. 例如,使用Json .NET JsonConverter序列化和反序列化对象。

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

Then you could read it back like this 然后你可以这样读回来

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM