You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.9 KiB

  1. using System.IO;
  2. using System.Runtime.Serialization.Formatters.Binary;
  3. using System.Text;
  4. using System.Xml;
  5. using System.Xml.Serialization;
  6. namespace NFine.Code
  7. {
  8. public static class Serialize
  9. {
  10. /// <summary>
  11. /// 获取对象序列化的二进制版本
  12. /// </summary>
  13. /// <param name="pObj">对象实体</param>
  14. /// <returns>如果对象实体为Null,则返回结果为Null。</returns>
  15. public static byte[] GetBytes(object pObj)
  16. {
  17. if (pObj == null) { return null; }
  18. MemoryStream serializationStream = new MemoryStream();
  19. new BinaryFormatter().Serialize(serializationStream, pObj);
  20. serializationStream.Position = 0L;
  21. byte[] buffer = new byte[serializationStream.Length];
  22. serializationStream.Read(buffer, 0, buffer.Length);
  23. serializationStream.Close();
  24. return buffer;
  25. }
  26. /// <summary>
  27. /// 获取对象序列化的XmlDocument版本
  28. /// </summary>
  29. /// <param name="pObj">对象实体</param>
  30. /// <returns>如果对象实体为Null,则返回结果为Null。</returns>
  31. public static XmlDocument GetXmlDoc(object pObj)
  32. {
  33. if (pObj == null) { return null; }
  34. XmlSerializer serializer = new XmlSerializer(pObj.GetType());
  35. StringBuilder sb = new StringBuilder();
  36. StringWriter writer = new StringWriter(sb);
  37. serializer.Serialize((TextWriter)writer, pObj);
  38. XmlDocument document = new XmlDocument();
  39. document.LoadXml(sb.ToString());
  40. writer.Close();
  41. return document;
  42. }
  43. /// <summary>
  44. /// 从已序列化数据中(byte[])获取对象实体
  45. /// </summary>
  46. /// <typeparam name="T">要返回的数据类型</typeparam>
  47. /// <param name="binData">二进制数据</param>
  48. /// <returns>对象实体</returns>
  49. public static T GetObject<T>(byte[] binData)
  50. {
  51. if (binData == null) { return default(T); }
  52. BinaryFormatter formatter = new BinaryFormatter();
  53. MemoryStream serializationStream = new MemoryStream(binData);
  54. return (T)formatter.Deserialize(serializationStream);
  55. }
  56. /// <summary>
  57. /// 从已序列化数据(XmlDocument)中获取对象实体
  58. /// </summary>
  59. /// <typeparam name="T">要返回的数据类型</typeparam>
  60. /// <param name="xmlDoc">已序列化的文档对象</param>
  61. /// <returns>对象实体</returns>
  62. public static T GetObject<T>(XmlDocument xmlDoc)
  63. {
  64. if (xmlDoc == null) { return default(T); }
  65. XmlNodeReader xmlReader = new XmlNodeReader(xmlDoc.DocumentElement);
  66. XmlSerializer serializer = new XmlSerializer(typeof(T));
  67. return (T)serializer.Deserialize(xmlReader);
  68. }
  69. }
  70. }