【问题标题】:Save custom Object to Application Settings does not work将自定义对象保存到应用程序设置不起作用
【发布时间】:2017-03-29 09:39:57
【问题描述】:

我在应用程序中有一个对象,用于保存该应用程序的设置。此对象的实例保存在应用程序的设置中。

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

在应用程序启动时,对象被读出,如果它的 null 则被实例化。之后立即保存。

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

当从设置对话框修改设置并应保存时,对象将保存到设置中。

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

但是,当我重新启动应用程序时,读出的对象再次为空。这发生在调试时以及当我尝试在不调试的情况下启动时。

我做错了什么?甚至可以将自定义对象保存到设置中吗?

【问题讨论】:

  • 当您调用Save() 时,您会修改用户的 设置。你的对象被标记为ApplicationScopedSetting。您是否尝试过使用 UserScopedSettingAttribute ?这不适用于 ASP.NET 应用程序,因为这些应用程序没有用户配置设置
  • @PanagiotisKanavos 是的,使用UseScopedSettingAttribute 可以。谢谢!

标签: c# .net application-settings


【解决方案1】:

似乎您想根据对象序列化您的设置。我建议使用Newtonsoft Json.NET

Serialize 将您的对象转换为 JSON 字符串,当您想将其保存到您的设置时。 Deserialize 读取设置时将设置字符串指向实际对象。

【讨论】:

  • 这不能回答问题。设置的 content 无关紧要。 .NET 使用复杂的设置对象没有问题
猜你喜欢
  • 1970-01-01
  • 2010-10-08
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
相关资源
最近更新 更多