当前位置:   article > 正文

C#--序列化和反序列化_c# serializer.serializevalue

c# serializer.serializevalue

序列化是指将对象转换成字节流,从而存储对象或将对象传输到内存、数据库或文件的过程。 它的主要用途是保存对象的状态,以便能够在需要时重新创建对象。 反向过程称为“反序列化”。


序列化的工作原理

下图展示了序列化的整个过程。



对象序列化

若要序列化对象,需要具有要序列化的对象、包含已序列化对象的一个流,以及一个 Formatter。

将 SerializableAttribute 特性应用于某个类型,以指示此类型的实例可以被序列化,具体做法在类之前加[Serializable]。

如果想让类中的某个字段不可序列化,请应用 NonSerializedAttribute 特性,具体做法在字段之前加[NonSerialized]。

C#代码实现:

  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. namespace NetFrame
  5. {
  6. public class SerializeUtil
  7. {
  8. /// <summary>
  9. /// 对象序列化
  10. /// </summary>
  11. /// <param name="value"></param>
  12. /// <returns></returns>
  13. public static byte[] Encode(object value)
  14. {
  15. //创建编码解码的内存流对象
  16. MemoryStream ms = new MemoryStream();
  17. //二进制流序列化对象
  18. BinaryFormatter bw = new BinaryFormatter();
  19. //将obj对象序列化成二进制数据 写入到 内存流
  20. bw.Serialize(ms, value);
  21. byte[] result = new byte[ms.Length];
  22. //将流数据 拷贝到结果数组
  23. Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);
  24. ms.Close();
  25. return result;
  26. }
  27. /// <summary>
  28. /// 反序列化对象
  29. /// </summary>
  30. /// <param name="value"></param>
  31. /// <returns></returns>
  32. public static object Decode(byte[] value)
  33. {
  34. //创建编码解码的内存流对象 并将需要反序列化的数据写入其中
  35. MemoryStream ms = new MemoryStream(value);
  36. //二进制流序列化对象
  37. BinaryFormatter bw = new BinaryFormatter();
  38. //将流数据反序列化为obj对象
  39. object result = bw.Deserialize(ms);
  40. ms.Close();
  41. return result;
  42. }
  43. }
  44. }

二进制和 XML 序列化

二进制序列化使用二进制编码来生成精简的序列化以供使用,如基于存储或套接字的网络流。

XML 序列化将对象的公共字段和属性或方法的参数和返回值序列化成符合特定 XML 架构定义语言 (XSD) 文档要求的 XML 流。

首先写一个需要序列化的类:

  1. [Serializable]
  2. public class ConfigMD5Data
  3. {
  4. public string fileName;
  5. public string excelMD5;
  6. public List<string> binaryMD5List;
  7. public List<string> classNameList;
  8. public List<string> typeNameList;
  9. [NonSerialized]
  10. public bool md5Changed;
  11. [NonSerialized]
  12. public bool classNameChanged;
  13. [NonSerialized]
  14. public bool binaryChanged;
  15. }
  16. [Serializable]
  17. public class ConfigMD5
  18. {
  19. public List<ConfigMD5Data> m_ConfigMD5List = new List<ConfigMD5Data>();
  20. }

二进制序列化的C#实现:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.Serialization;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. namespace StructScript
  7. {
  8. class BinaryFormatterTest
  9. {
  10. private static string m_ConfigMD5Path1;
  11. private static ConfigMD5 m_ConfigList;
  12. private static void Main(string[] args)
  13. {
  14. m_ConfigMD5Path1 = "config.bytes";
  15. m_ConfigList = new ConfigMD5();
  16. for (int i = 0; i < 5; i++)
  17. {
  18. ConfigMD5Data data = new ConfigMD5Data();
  19. data.fileName = "test" + i;
  20. m_ConfigList.m_ConfigMD5List.Add(data);
  21. }
  22. Serialize();
  23. Deserialize();
  24. Console.ReadLine();
  25. }
  26. private static void Serialize()
  27. {
  28. FileStream fs = new FileStream(m_ConfigMD5Path1, FileMode.Create);
  29. BinaryFormatter formatter = new BinaryFormatter();
  30. try
  31. {
  32. formatter.Serialize(fs, m_ConfigList);
  33. }
  34. catch (SerializationException e)
  35. {
  36. Console.WriteLine("Failed to serialize. Reason: " + e.Message);
  37. }
  38. finally
  39. {
  40. fs.Close();
  41. }
  42. }
  43. private static void Deserialize()
  44. {
  45. if (File.Exists(m_ConfigMD5Path1))
  46. {
  47. FileStream fs = new FileStream(m_ConfigMD5Path1, FileMode.Open);
  48. try
  49. {
  50. BinaryFormatter formatter = new BinaryFormatter();
  51. m_ConfigList = formatter.Deserialize(fs) as ConfigMD5;
  52. int count = m_ConfigList.m_ConfigMD5List.Count;
  53. for (int i = 0; i < count; i++)
  54. {
  55. ConfigMD5Data data = m_ConfigList.m_ConfigMD5List[i];
  56. Console.WriteLine(data.fileName);
  57. }
  58. }
  59. catch (SerializationException e)
  60. {
  61. Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
  62. }
  63. finally
  64. {
  65. fs.Close();
  66. }
  67. }
  68. }
  69. [Serializable]
  70. public class ConfigMD5Data
  71. {
  72. public string fileName;
  73. public string excelMD5;
  74. public List<string> binaryMD5List;
  75. public List<string> classNameList;
  76. public List<string> typeNameList;
  77. [NonSerialized]
  78. public bool md5Changed;
  79. [NonSerialized]
  80. public bool classNameChanged;
  81. [NonSerialized]
  82. public bool binaryChanged;
  83. }
  84. [Serializable]
  85. public class ConfigMD5
  86. {
  87. public List<ConfigMD5Data> m_ConfigMD5List = new List<ConfigMD5Data>();
  88. }
  89. }
  90. }

输出结果:


Xml序列化C#实现:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml.Serialization;
  6. namespace StructScript
  7. {
  8. public class XmlFormatterTest
  9. {
  10. private static string m_ConfigMD5Path;
  11. private static ConfigMD5 m_ConfigList;
  12. private static void Main(string[] args)
  13. {
  14. m_ConfigMD5Path = "config.xml";
  15. m_ConfigList = new ConfigMD5();
  16. for (int i = 0; i < 5; i++)
  17. {
  18. ConfigMD5Data data = new ConfigMD5Data();
  19. data.fileName = "test" + i;
  20. m_ConfigList.m_ConfigMD5List.Add(data);
  21. }
  22. SaveXml();
  23. LoadXml();
  24. Console.ReadLine();
  25. }
  26. public static bool SaveXml()
  27. {
  28. DeleteFile(m_ConfigMD5Path);
  29. using (StreamWriter sw = new StreamWriter(m_ConfigMD5Path, false, Encoding.UTF8))
  30. {
  31. XmlSerializer serializer = new XmlSerializer(typeof(ConfigMD5));
  32. try
  33. {
  34. serializer.Serialize(sw, m_ConfigList);
  35. }
  36. catch (Exception e)
  37. {
  38. Console.WriteLine("Load ConfigMD5 fail, error: " + e.Message);
  39. }
  40. }
  41. return true;
  42. }
  43. public static bool DeleteFile(string filePath)
  44. {
  45. if (File.Exists(filePath))
  46. {
  47. File.Delete(filePath);
  48. return true;
  49. }
  50. return false;
  51. }
  52. public static void LoadXml()
  53. {
  54. if (File.Exists(m_ConfigMD5Path))
  55. {
  56. try
  57. {
  58. using (StreamReader sr = new StreamReader(m_ConfigMD5Path, Encoding.UTF8))
  59. {
  60. XmlSerializer serializer = new XmlSerializer(typeof(ConfigMD5));
  61. m_ConfigList = serializer.Deserialize(sr) as ConfigMD5;
  62. int count = m_ConfigList.m_ConfigMD5List.Count;
  63. for (int i = 0; i < count; i++)
  64. {
  65. ConfigMD5Data data = m_ConfigList.m_ConfigMD5List[i];
  66. Console.WriteLine(data.fileName);
  67. }
  68. }
  69. }
  70. catch (Exception e)
  71. {
  72. Console.WriteLine("Load ConfigMD5 fail, error: " + e.Message);
  73. }
  74. }
  75. }
  76. [Serializable]
  77. public class ConfigMD5Data
  78. {
  79. public string fileName;
  80. public string excelMD5;
  81. public List<string> binaryMD5List;
  82. public List<string> classNameList;
  83. public List<string> typeNameList;
  84. [NonSerialized]
  85. public bool md5Changed;
  86. [NonSerialized]
  87. public bool classNameChanged;
  88. [NonSerialized]
  89. public bool binaryChanged;
  90. }
  91. [Serializable]
  92. public class ConfigMD5
  93. {
  94. public List<ConfigMD5Data> m_ConfigMD5List = new List<ConfigMD5Data>();
  95. }
  96. }
  97. }

输出结果:



总结:

在二进制序列化中,所有成员(包括只读成员)都会被序列化,且性能也会有所提升。 XML 序列化可提高代码可读性,以及对象共享和使用的灵活性,从而实现互操作性。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/111878
推荐阅读
相关标签
  

闽ICP备14008679号