簡體   English   中英

如何通過applicationsettingsbase重新加載不同的對象?

[英]How to reload different objects by applicationsettingsbase?

// TestASettingsString and TestBSettingsString are byte[]
// TestASettings and TestBSettings are two objects to be saved

在SettingsSaving中,將TestASettings和TestBSettings序列化為兩個單獨的字節數組,然后保存(在某些其他函數中)

我的問題是如何從loadavedsettings中的TestASettingsString和TestASettingsString中分別恢復TestASettings和TestBSettings?

那就是我做formatter.Deserialize(stream);的時候。

如何將兩個完全不同的對象TestASettings和TestBSettings與formatter.Deserialize(stream)分開?

謝謝

private void SettingsSaving(object sender, CancelEventArgs e)
    {

        try
        {
            var stream = new MemoryStream();
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, TestASettings);
    // TestASettingsString and TestBSettingsString are byte[]
            TestASettingsString = stream.ToArray();

            stream.Flush();
            formatter.Serialize(stream, TestBSettings);
            TestBSettingsString = stream.ToArray();   

            stream.Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
    }





private void LoadSavedSettings()
    {
        Reload();
        // how to get TestASettings and TestBSettings from TestASettingsString  and
        // TestASettingsString seperately?
    }

我懷疑部分問題在這里:

        TestASettingsString = stream.ToArray();
        stream.Flush();
        formatter.Serialize(stream, TestBSettings);
        TestBSettingsString = stream.ToArray();  

對於MemoryStreamFlush()是無操作的。 您實際上是說:

        TestASettingsString = stream.ToArray();
        stream.SetLength(0);
        formatter.Serialize(stream, TestBSettings);
        TestBSettingsString = stream.ToArray();  

哪個將重置流,將TestBSettingsString作為單獨的數據塊提供? 當前, TestBSettingsString實際上包含TestASettingsTestBSettings

完成此操作后,應該只是扭轉情況:

using(MemoryStream ms = new MemoryStream(TestASettingsString)) {
    BinaryFormatter bf = new BinaryFormatter();
    TestASettings = (WhateverType)bf.Deserialize(ms);
}
using(MemoryStream ms = new MemoryStream(TestBSettingsString)) {
    BinaryFormatter bf = new BinaryFormatter();
    TestBSettings = (WhateverOtherType)bf.Deserialize(ms);
}

另請注意:我建議不要使用BinaryFormatter持久存儲任何離線內容(磁盤,數據庫等)。

反序列化它們需要如下代碼:

var ms = new MemoryStream(TestASettingsString);
var fmt = new BinaryFormatter();
TestASettings = (TestAClass)fmt.Deserialize(ms);

其中,TestAClass是TestASettings的類型。 您需要在序列化代碼中重置流,將Position設置回0。

暫無
暫無

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

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