经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » XML相关 » XML » 查看文章
C#使用BinaryFormatter类、ISerializable接口、XmlSerializer类进行序列化和反序列化
来源:jb51  时间:2022/9/15 9:09:23  对本文有异议

序列化是将对象转换成字节流的过程,反序列化是把字节流转换成对象的过程。对象一旦被序列化,就可以把对象状态保存到硬盘的某个位置,甚至还可以通过网络发送给另外一台机器上运行的进程。本篇主要包括:

使用BinaryFormatter类进行序列化和反序列化

使用ISerializable接口自定义序列化过程

使用XmlSerializer类进行序列化和反序列化

使用BinaryFormatter类进行序列化和反序列化

首先把需要序列化的类打上[Serializable]特性,如果某个字段不需要被序列化,就打上[NonSerialized]特性。

  1. [Serializable]
  2. public class Meeting
  3. {
  4. public string _name;
  5. [NonSerialized]
  6. public string _location;
  7. public Meeting(string name, string location)
  8. {
  9. this._name = name;
  10. this._location = location;
  11. }
  12. }

对象序列化后需要一个载体文件,以下的Meeting.binary文件用来存储对象的状态。

  1. static void Main(string[] args)
  2. {
  3. Meeting m1 = new Meeting("年终总结","青岛");
  4. Meeting m2;
  5. //先序列化
  6. SerializedWithBinaryFormatter(m1,"Meeting.binary");
  7. m2 = (Meeting) DeserializeWithBinaryFormatter("Meeting.binary");
  8. Console.WriteLine(m2._name);
  9. Console.WriteLine(m2._location ?? "_location字段没有被序列化");
  10. Console.ReadKey();
  11. }
  12. //序列化
  13. static void SerializedWithBinaryFormatter(object obj, string fileName)
  14. {
  15. //打开文件写成流
  16. Stream streamOut = File.OpenWrite(fileName);
  17. BinaryFormatter formatter = new BinaryFormatter();
  18. //把对象序列化到流中
  19. formatter.Serialize(streamOut, obj);
  20. //关闭流
  21. streamOut.Close();
  22. }
  23. //反序列化
  24. static object DeserializeWithBinaryFormatter(string fileName)
  25. {
  26. //打开文件读成流
  27. Stream streamIn = File.OpenRead(fileName);
  28. BinaryFormatter formatter = new BinaryFormatter();
  29. object obj = formatter.Deserialize(streamIn);
  30. streamIn.Close();
  31. return obj;
  32. }

Meeting.binary文件在bin/debug文件夹中。

使用ISerializable接口自定义序列化过程

如果想对序列化的过程有更多的控制,应该使用ISerializable接口,通过它的GetObjectData方法可以改变对象的字段值。

  1. [Serializable]
  2. public class Location : ISerializable
  3. {
  4. public int x;
  5. public int y;
  6. public string name;
  7. public Location(int x, int y, string name)
  8. {
  9. this.x = x;
  10. this.y = y;
  11. this.name = name;
  12. }
  13. protected Location(SerializationInfo info, StreamingContext context)
  14. {
  15. x = info.GetInt32("i");
  16. y = info.GetInt32("j");
  17. name = info.GetString("k");
  18. }
  19. public void GetObjectData(SerializationInfo info, StreamingContext context)
  20. {
  21. info.AddValue("i", x + 1);
  22. info.AddValue("j", y + 1);
  23. info.AddValue("k", name + "HELLO");
  24. }
  25. }

以上,不仅要实现接口方法GetObjectData,还需要提供对象的重载构造函数,从SerializationInfo实例中获取值。

在客户端:

  1. Location loc1 = new Location(1,2,"qingdao");
  2. Location loc2;
  3. //序列化
  4. SerializedWithBinaryFormatter(loc1, "Location.binary");
  5. loc2 = (Location) DeserializeWithBinaryFormatter("Location.binary");
  6. Console.WriteLine(loc2.x);
  7. Console.WriteLine(loc2.y);
  8. Console.WriteLine(loc2.name);
  9. Console.ReadKey();

以上,使用BinaryFormatter类进行序列化和反序列化,存储的文件格式是二进制的,例如,打开Meeting.binary文件,我们看到:

有时候,我们希望文件的格式是xml。

使用XmlSerializer类进行序列化和反序列化

XmlSerializer类进行序列化的存储文件是xml格式。用XmlSerializer类进行序列化的类不需要打上[Serializable]特性。

  1. public class Car
  2. {
  3. [XmlAttribute(AttributeName = "model")]
  4. public string type;
  5. public string code;
  6. [XmlIgnore]
  7. public int age;
  8. [XmlElement(ElementName = "mileage")]
  9. public int miles;
  10. public Status status;
  11. public enum Status
  12. {
  13. [XmlEnum("使用中")]
  14. Normal,
  15. [XmlEnum("修复中")]
  16. NotUse,
  17. [XmlEnum("不再使用")]
  18. Deleted
  19. }
  20. }

在客户端:

  1. //打开写进流
  2. Stream streamOut = File.OpenWrite("Car.xml");
  3. System.Xml.Serialization.XmlSerializer x = new XmlSerializer(car1.GetType());
  4. //序列化到流中
  5. x.Serialize(streamOut, car1);
  6. streamOut.Close();
  7. //打开读流
  8. Stream streamIn = File.OpenRead("Car.xml");
  9. //反序列化
  10. Car car2 = (Car) x.Deserialize(streamIn);
  11. Console.WriteLine(car2.type);
  12. Console.WriteLine(car2.code);
  13. Console.WriteLine(car2.miles);
  14. Console.WriteLine(car2.status);
  15. Console.ReadKey();

运行,打开bin/debug中的Car.xml文件如下:

  1. <?xml version="1.0"?>
  2. <Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" model="sedan">
  3. <code>001</code>
  4. <mileage>1000</mileage>
  5. <status>使用中</status>
  6. </Car>
  • 类名Car成了xml的根节点
  • 打上[XmlAttribute(AttributeName = "model")]特性的字段变成了根节点的属性,AttributeName为属性别名
  • 枚举项可打上[XmlEnum("使用中")]特性

如果一个类中包含集合属性,比如以下的Department类包含一个类型List<Employee>的集合属性Employees。

  1. public class Department
  2. {
  3. public Department()
  4. {
  5. Employees = new List<Employee>();
  6. }
  7. public string Name { get; set; }
  8. [XmlArray("Staff")]
  9. public List<Employee> Employees { get; set; }
  10. }
  11. public class Employee
  12. {
  13. public string Name { get; set; }
  14. public Employee()
  15. {
  16. }
  17. public Employee(string name)
  18. {
  19. Name = name;
  20. }
  21. }

在客户端:

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. var department = new Department();
  6. department.Name = "销售部";
  7. department.Employees.Add(new Employee("张三"));
  8. department.Employees.Add(new Employee("李四"));
  9. XmlSerializer serializer = new XmlSerializer(department.GetType());
  10. //打开写进流
  11. Stream streamOut = File.OpenWrite("Department.xml");
  12. serializer.Serialize(streamOut, department);
  13. streamOut.Close();
  14. }
  15. }

查看bin/debug中的Department.xml文件。

  1. <?xml version="1.0"?>
  2. <Department xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3. <Name>销售部</Name>
  4. <Staff>
  5. <Employee>
  6. <Name>张三</Name>
  7. </Employee>
  8. <Employee>
  9. <Name>李四</Name>
  10. </Employee>
  11. </Staff>
  12. </Department>

总结:

  • 1、使用BinaryFormatter类序列化到二进制文件
  • 2、使用XmlSerializer类序列化到xml文件
  • 3、使用ISerializable接口自定义序列化过程

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对w3xue的支持。如果你想了解更多相关内容请查看下面相关链接

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号