简体   繁体   English

将自定义对象保存到应用程序设置不起作用

[英]Save custom Object to Application Settings does not work

I have a object in an application that saves settings for this application. 我在应用程序中有一个对象,用于保存该应用程序的设置。 The instance of this object is saved in the settings of the application. 该对象的实例保存在应用程序的设置中。

[global::System.Configuration.ApplicationScopedSetting()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public ReportingConfiguration ReportingConfiguration
{
    get { return ((ReportingConfiguration)(this["ReportingConfiguration"])); }
    set { this["ReportingConfiguration"] = value; }
}

At application start up the object is read out and if its null new instantiated. 在应用程序启动时,将读取对象,如果实例化为null,则将其实例化。 After that immediately saved. 之后立即保存。

// Get existing ReportingConfiguration or create new if null
var reportingConfiguration = Properties.Settings.Default.ReportingConfiguration;
if (reportingConfiguration == null)
{
    reportingConfiguration = new ReportingConfiguration();
    Properties.Settings.Default.ReportingConfiguration = reportingConfiguration;
    Properties.Settings.Default.Save();
}

When the settings are modified from the settings dialog and should be saved, the object is saved to the settings. 从设置对话框修改设置并保存设置后,对象将保存到设置中。

Properties.Settings.Default.ReportingConfiguration = _reportingConfiguration;
Properties.Settings.Default.Save();

However, when I restart the application, the read out object is null again. 但是,当我重新启动应用程序时,读出的对象再次为null。 This happens at debugging and also when I try it to start without debugging. 这在调试时以及在尝试不进行调试就启动时都会发生。

What am I doing wrong? 我究竟做错了什么? Is it even possible to save a custom object to settings? 甚至可以将自定义对象保存到设置中吗?

Seems like you want to serialize your settings based on objects. 似乎您想基于对象序列化设置。 I would recommend using Newtonsoft Json.NET . 我建议使用Newtonsoft Json.NET

Serialize your object into a JSON string when ever you want to save it to your settings. 要将对象保存到设置时,将其序列化为JSON字符串。 Deserialize the setting string to the actual object when reading out your setting. 读取设置时,将设置字符串反序列化为实际对象。

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

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