// TestASettingsString and TestBSettingsString are byte[]
// TestASettings and TestBSettings are two objects to be saved
在SettingsSaving中,TestASettings和TestBSettings被序列化为两个单独的字节数组,然后保存(在其他一些函数中)
我的问题是如何在loadsavedsettings中单独从TestASettingString和TestASettingsString中恢复TestASettings和TestBSettings?
那是我的时候 formatter.Deserialize(流);
如何从formatter.Deserialize(stream)中分离两个完全不同的对象TestASettings和TestBSettings?
由于
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?
}
答案 0 :(得分:1)
我怀疑问题的一部分在这里:
TestASettingsString = stream.ToArray();
stream.Flush();
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
对于MemoryStream
,Flush()
是无操作。你的意思是:
TestASettingsString = stream.ToArray();
stream.SetLength(0);
formatter.Serialize(stream, TestBSettings);
TestBSettingsString = stream.ToArray();
会重置流,将TestBSettingsString
作为单独的数据块?目前TestBSettingsString
实际上包含TestASettings
和TestBSettings
。
完成后,它应该是一个扭转事物的案例:
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
将任何内容保持脱机状态(磁盘,数据库等)。
答案 1 :(得分:1)
反序列化它们需要这样的代码:
var ms = new MemoryStream(TestASettingsString);
var fmt = new BinaryFormatter();
TestASettings = (TestAClass)fmt.Deserialize(ms);
TestAClass是TestASettings的类型。您需要在序列化代码中重置流,将Position设置回0。