簡體   English   中英

將自定義對象保存到應用程序設置不起作用

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

我在應用程序中有一個對象,用於保存該應用程序的設置。 該對象的實例保存在應用程序的設置中。

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

但是,當我重新啟動應用程序時,讀出的對象再次為null。 這在調試時以及在嘗試不進行調試就啟動時都會發生。

我究竟做錯了什么? 甚至可以將自定義對象保存到設置中嗎?

似乎您想基於對象序列化設置。 我建議使用Newtonsoft Json.NET

要將對象保存到設置時,將其序列化為JSON字符串。 讀取設置時,將設置字符串反序列化為實際對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM