反序列化后的对象关联

时间:2018-10-19 13:00:05

标签: object serialization deserialization

我创建了三个类:“联系人”类,其中包含电话联系人的姓名和电话号码; “列表”类,其中包含描述和“联系人”列表;包含“列表”列表的“归档”类。 创建存档后,我将其序列化。

反序列化之后,属于不同列表的联系人之间不再有任何对应关系,这些联系人最初是单个联系人。

如果您更改两个列表之一中的联系人的属性,则此更改不会传播到第二个列表中的联系人。

反序列化后是否可以保留对象的身份?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        Test();
    }

    private static void Test()
    {
        Contact c1 = new Contact();
        c1.name = "Albert";
        c1.phone_number = "111-111111";
        Contact c2 = new Contact();
        c2.name = "Enrico";
        c2.phone_number = "111-222222";
        Contact c3 = new Contact();
        c3.name = "Niels";
        c3.phone_number = "111-333333";
        Contact c4 = new Contact();
        c4.name = "Richard";
        c4.phone_number = "111-444444";
        Contact c5 = new Contact();
        c5.name = "Marie";
        c5.phone_number = "111-555555";

        List list1 = new List();
        list1.description = "USA list";
        list1.contacts.Add(c4);
        list1.contacts.Add(c1);

        List list2 = new List();
        list2.description = "EU list";
        list2.contacts.Add(c1);
        list2.contacts.Add(c2);
        list2.contacts.Add(c3);
        list2.contacts.Add(c5);

        Archive arc = new Archive();
        arc.lists.Add(list1);
        arc.lists.Add(list2);

        Archive.Serialize(Directory.GetCurrentDirectory() + "\\archive.xml", arc);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Archive arc_readed;
        Archive.Deserialize(Directory.GetCurrentDirectory() + "\\archive.xml", out arc_readed);
        arc_readed.lists[0].contacts[1].name = "Albert Einstein";
    }
}

public class Contact
{
    public string name;
    public string phone_number;
}

public class List
{
    public string description;
    public List<Contact> contacts = new List<Contact>();
}

public class Archive
{
    public List<List> lists = new List<List>();

    public static bool Serialize(string filename, Archive isp)
    {
        XmlSerializer serializer = new XmlSerializer(isp.GetType());
        Stream fs = new FileStream(filename, FileMode.Create);
        XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode);
        serializer.Serialize(writer, isp);
        writer.Close();
        fs.Close();
        return true;
    }

    public static bool Deserialize(string filename, out Archive df)
    {
        if (File.Exists(filename))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Archive));
            Archive i;
            using (Stream reader = new FileStream(filename, FileMode.Open))
            {
                i = (Archive)serializer.Deserialize(reader);
            }
            df = i;
            return true;
        }
        else
        {
            df = null;
            return false;
        }
    }
}

0 个答案:

没有答案