.NET中制做对象的副本(三)通过序列化和反序列化为复杂对象制作副本
1、类的定义
/// <summary> /// 学生信息 /// </summary> [Serializable] public class Stu { /// <summary> /// 学生姓名 /// </summary> public string Name { get; set; } /// <summary> /// 学生的老师 /// </summary> public List<Teacher> Teachers { get; set; } } /// <summary> /// 老师信息 /// </summary> [Serializable] public class Teacher { /// <summary> /// 老师姓名 /// </summary> public string Name { get; set; } /// <summary> /// 学生列表 /// </summary> public List<Stu> Stus { get; set; } }
2、实例化对象
这个学生类型比较复杂,和老师发生了循环引用。
Stu stu = new Stu() { Name = "马良", Teachers = new List<Teacher>() { new Teacher() { Name="老师1", Stus=new List<Stu> (){} } } }; stu.Teachers[0].Stus.Add(stu);
3、对对象进行拷贝
BinaryFormatter bfSerialize = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bfSerialize.Serialize(ms, stu); BinaryFormatter bfDeserialize = new BinaryFormatter(); ms.Position = 0; Stu stu1 = (Stu)bfDeserialize.Deserialize(ms);
漫思