简体   繁体   English

如何序列化不同类型的多个对象?

[英]How to serialize multiple objects of different types?

I'm trying to serialize an array of objects and a string. 我正在尝试序列化对象数组和字符串。 This is the serialization code: 这是序列化代码:

FileStream s;
s = new FileStream(savefile.FileName, FileMode.Create, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(s, ch.chaps);
bf.Serialize(s, txtPassword.Text);
s.Close();

This is the deserialization code: 这是反序列化代码:

FileStream s;
s = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
string password = (string)bf.Deserialize(s);
ch.chaps = (Chapter[])bf.Deserialize(s);
s.Close();
int i;

if (password == txtPassword.Text)
{
    for (i = 0; i <= 1000; i++)
    {
        try
        {
            combChapSelect.Items.Add(ch.chaps[i].chapName);         
        }
        catch
        {
             i = 1000;
        }
    }
}

This is the code and visual studio says there are no errors but the openfiledialog doesn't close when I select a file and nothing happens. 这是代码,Visual Studio表示没有错误,但是当我选择一个文件并且没有任何反应时,openfile对话框没有关闭。 Have I done something wrong or is there another way to serialize different object types? 我做错了什么,还是有另一种方法来序列化不同的对象类型?

You're doing this backwards. 您正在这样做。 You have to deserialize in the same order that you serialize. 您必须按照序列化的顺序反序列化。

In your serialization, its chaps-then-password. 在您的序列化过程中,它首先破解了密码。 In your deserialization, its password-then-chaps. 在反序列化过程中,其密码随后会破裂。

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

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