当前位置:   article > 正文

c# 自定义可序列化_c# 自定义序列化

c# 自定义序列化

 一、定义一个序列化的类(包含二进制,xml,json 三种方法)

 

  1. public class SerializeHelper
  2. {
  3. #region 私有的
  4. #region 字段
  5. #endregion
  6. #region 方法
  7. #endregion
  8. #endregion
  9. #region 保护的
  10. #region 字段
  11. #endregion
  12. #region 方法
  13. #endregion
  14. #endregion
  15. #region 公开的
  16. #region 属性
  17. #endregion
  18. #region 方法
  19. #endregion
  20. #endregion
  21. #region 静态方法
  22. #region 二进制方式
  23. /// <summary>
  24. /// 序列化对像
  25. /// </summary>
  26. /// <param name="obj"></param>
  27. /// <param name="FileName"></param>123456
  28. /// <param name="Exception">是否显示异常消息</param>
  29. /// <returns></returns>
  30. public static bool Serialize(object obj, string FileName, bool showException)
  31. {
  32. FileInfo fi = new FileInfo(FileName);
  33. if (!fi.Directory.Exists) fi.Directory.Create();
  34. using (FileStream fileStream = new FileStream(FileName, FileMode.Create))
  35. {
  36. try
  37. {
  38. BinaryFormatter b = new BinaryFormatter();
  39. b.Serialize(fileStream, obj);
  40. return true;
  41. }
  42. catch (Exception ex)
  43. {
  44. if (showException)
  45. {
  46. throw new Exception(ex.Message);
  47. }
  48. return false;
  49. }
  50. }
  51. }
  52. /// <summary>
  53. /// 序列化对像
  54. /// </summary>
  55. /// <param name="obj"></param>
  56. /// <param name="FileName"></param>123456
  57. /// <param name="Exception">是否显示异常消息</param>
  58. /// <returns></returns>
  59. public static byte[] Serialize(object obj,bool showException)
  60. {
  61. using (MemoryStream fileStream = new MemoryStream())
  62. {
  63. try
  64. {
  65. BinaryFormatter b = new BinaryFormatter();
  66. b.Serialize(fileStream, obj);
  67. return fileStream.ToArray();
  68. }
  69. catch (Exception ex)
  70. {
  71. if (showException)
  72. {
  73. throw new Exception(ex.Message);
  74. }
  75. return null;
  76. }
  77. }
  78. }
  79. /// <summary>
  80. /// 反序列化对像
  81. /// </summary>
  82. /// <param name="FileName"></param>
  83. /// <param name="showException">是否显示异常消息</param>
  84. /// <returns></returns>
  85. public static object DeSerialize(string FileName, bool showException)
  86. {
  87. return DeSerialize(FileName, showException);
  88. }
  89. /// <summary>
  90. /// 反序列化对像
  91. /// </summary>
  92. /// <param name="FileName"></param>
  93. /// <param name="showException">是否显示异常消息</param>
  94. /// <returns></returns>
  95. public static object DeSerialize(byte[] inputBuf, bool showException)
  96. {
  97. return DeSerialize<object>(inputBuf, showException);
  98. }
  99. /// <summary>
  100. /// 反序列化对像
  101. /// </summary>
  102. /// <typeparam name="T">返回的类型</typeparam>
  103. /// <param name="FileName"></param>
  104. /// <param name="showException">是否显示异常消息</param>
  105. /// <returns></returns>
  106. public static T DeSerialize<T>(string FileName, bool showException)
  107. {
  108. if (!System.IO.File.Exists(FileName))
  109. {
  110. if (showException) throw new Exception("文件不存");
  111. return default(T);
  112. }
  113. using (FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  114. {
  115. try
  116. {
  117. BinaryFormatter b = new BinaryFormatter();
  118. b.Binder = new ObjBinderEx<T>();
  119. object obj = b.Deserialize(fileStream);
  120. return (T)obj;
  121. }
  122. catch (Exception ex)
  123. {
  124. if (showException)
  125. {
  126. throw new Exception(ex.Message);
  127. }
  128. return default(T);
  129. }
  130. }
  131. }
  132. /// <summary>
  133. /// 反序列化对像
  134. /// </summary>
  135. /// <typeparam name="T">返回的类型</typeparam>
  136. /// <param name="FileName"></param>
  137. /// <param name="showException">是否显示异常消息</param>
  138. /// <returns></returns>
  139. public static T DeSerialize<T>(byte[] inputBuf, bool showException)
  140. {
  141. using (MemoryStream fileStream = new MemoryStream(inputBuf))
  142. {
  143. try
  144. {
  145. BinaryFormatter b = new BinaryFormatter();
  146. b.Binder = new ObjBinderEx<T>();
  147. object obj = b.Deserialize(fileStream);
  148. return (T)obj;
  149. }
  150. catch (Exception ex)
  151. {
  152. if (showException)
  153. {
  154. throw new Exception(ex.Message);
  155. }
  156. return default(T);
  157. }
  158. }
  159. }
  160. #endregion
  161. #region XML方式
  162. /// <summary>
  163. /// 序列化对像
  164. /// </summary>
  165. /// <param name="obj"></param>
  166. /// <param name="FileName"></param>
  167. /// <param name="Exception">是否显示异常消息</param>
  168. /// <returns></returns>
  169. public static bool XMLSerialize(object obj, string FileName, bool showException)
  170. {
  171. FileInfo fi = new FileInfo(FileName);
  172. if (!fi.Directory.Exists) fi.Directory.Create();
  173. using (FileStream fileStream = new FileStream(FileName, FileMode.Create))
  174. {
  175. try
  176. {
  177. XmlSerializer b = new XmlSerializer(obj.GetType());
  178. b.Serialize(fileStream, obj);
  179. return true;
  180. }
  181. catch (Exception ex)
  182. {
  183. if (showException)
  184. {
  185. throw new Exception(ex.Message);
  186. }
  187. return false;
  188. }
  189. }
  190. }
  191. /// <summary>
  192. /// 序列化对像
  193. /// </summary>
  194. /// <param name="obj"></param>
  195. /// <param name="FileName"></param>
  196. /// <param name="Exception">是否显示异常消息</param>
  197. /// <returns></returns>
  198. public static byte[] XMLSerialize(object obj, bool showException)
  199. {
  200. using (MemoryStream fileStream = new MemoryStream())
  201. {
  202. try
  203. {
  204. XmlSerializer b = new XmlSerializer(obj.GetType());
  205. b.Serialize(fileStream, obj);
  206. return fileStream.ToArray() ;
  207. }
  208. catch (Exception ex)
  209. {
  210. if (showException)
  211. {
  212. throw new Exception(ex.Message);
  213. }
  214. return null;
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// 反序列化对像
  220. /// </summary>
  221. /// <param name="FileName"></param>
  222. /// <param name="showException">是否显示异常消息</param>
  223. /// <typeparam name="T">返回对像的类型</typeparam>
  224. /// <returns></returns>
  225. public static T XMLDeSerialize<T>(string FileName, bool showException)
  226. {
  227. if (!System.IO.File.Exists(FileName))
  228. {
  229. if (showException) throw new Exception("文件不存");
  230. return default(T);
  231. }
  232. using (FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
  233. {
  234. try
  235. {
  236. XmlSerializer b = new XmlSerializer(typeof(T));
  237. T obj = (T)b.Deserialize(fileStream);
  238. return obj;
  239. }
  240. catch (Exception ex)
  241. {
  242. if (showException)
  243. {
  244. throw new Exception(ex.Message);
  245. }
  246. return default(T);
  247. }
  248. }
  249. }
  250. /// <summary>
  251. /// 反序列化对像
  252. /// </summary>
  253. /// <param name="FileName"></param>
  254. /// <param name="showException">是否显示异常消息</param>
  255. /// <typeparam name="T">返回对像的类型</typeparam>
  256. /// <returns></returns>
  257. public static T XMLDeSerialize<T>(byte[] inputBuf, bool showException)
  258. {
  259. using (MemoryStream fileStream = new MemoryStream(inputBuf))
  260. {
  261. try
  262. {
  263. XmlSerializer b = new XmlSerializer(typeof(T));
  264. T obj = (T)b.Deserialize(fileStream);
  265. return obj;
  266. }
  267. catch (Exception ex)
  268. {
  269. if (showException)
  270. {
  271. throw new Exception(ex.Message);
  272. }
  273. return default(T);
  274. }
  275. }
  276. }
  277. #endregion
  278. #region Json方式
  279. public static string ToJson(object obj,bool showException)
  280. {
  281. try
  282. {
  283. return Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
  284. }
  285. catch (Exception ex)
  286. {
  287. if (showException)
  288. {
  289. throw new Exception(ex.Message);
  290. }
  291. return null;
  292. }
  293. }
  294. /// <summary>
  295. /// 序列化对像
  296. /// </summary>
  297. /// <param name="obj"></param>
  298. /// <param name="FileName"></param>
  299. /// <param name="Exception">是否显示异常消息</param>
  300. /// <returns></returns>
  301. public static bool JsonSerialize(object obj, string FileName, bool showException)
  302. {
  303. FileInfo fi = new FileInfo(FileName);
  304. if (!fi.Directory.Exists) fi.Directory.Create();
  305. try
  306. {
  307. var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
  308. File.WriteAllText(FileName, jsonStr, Encoding.UTF8);
  309. return true;
  310. }
  311. catch (Exception ex)
  312. {
  313. if (showException)
  314. {
  315. throw new Exception(ex.Message);
  316. }
  317. return false;
  318. }
  319. }
  320. /// <summary>
  321. /// 反序列化对像
  322. /// </summary>
  323. /// <param name="FileName"></param>
  324. /// <param name="showException">是否显示异常消息</param>
  325. /// <typeparam name="T">返回对像的类型</typeparam>
  326. /// <returns></returns>
  327. public static T JsonDeSerialize<T>(string FileName, bool showException)
  328. {
  329. if (!System.IO.File.Exists(FileName))
  330. {
  331. if (showException) throw new Exception("文件不存");
  332. return default(T);
  333. }
  334. try
  335. {
  336. var jsonStr = File.ReadAllText(FileName, Encoding.UTF8);
  337. var obj = JsonConvert.DeserializeObject<T>(jsonStr);
  338. return obj;
  339. }
  340. catch (Exception ex)
  341. {
  342. if (showException)
  343. {
  344. throw new Exception(ex.Message);
  345. }
  346. return default(T);
  347. }
  348. }
  349. /// <summary>
  350. /// 反序列化对像
  351. /// </summary>
  352. /// <param name="FileName"></param>
  353. /// <param name="showException">是否显示异常消息</param>
  354. /// <typeparam name="T">返回对像的类型</typeparam>
  355. /// <returns></returns>
  356. public static T FromJson<T>(string jsonStr, bool showException)
  357. {
  358. if (!string.IsNullOrEmpty(jsonStr))
  359. {
  360. if (showException) throw new Exception("空字符串");
  361. return default(T);
  362. }
  363. try
  364. {
  365. var obj = JsonConvert.DeserializeObject<T>(jsonStr);
  366. return obj;
  367. }
  368. catch (Exception ex)
  369. {
  370. if (showException)
  371. {
  372. throw new Exception(ex.Message);
  373. }
  374. return default(T);
  375. }
  376. }
  377. #endregion
  378. /// <summary>
  379. /// 将对像的属性序列化到本地
  380. /// </summary>
  381. /// <param name="obj"></param>
  382. /// <param name="filename"></param>
  383. /// <returns></returns>
  384. public static bool SerializePropertys(object obj, string FileName)
  385. {
  386. FileInfo fi = new FileInfo(FileName);
  387. if (!fi.Directory.Exists) fi.Directory.Create();
  388. PropertyInfo[] pis = obj.GetType().GetProperties();
  389. SerializeHash dict = new SerializeHash();
  390. foreach (PropertyInfo pi in pis)
  391. {
  392. if (!pi.CanWrite) continue;
  393. if (pi.GetIndexParameters().Length > 0) continue;
  394. Type t = pi.PropertyType;
  395. if ((t == typeof(string)) || (t == typeof(int)) || (t == typeof(short)) || (t == typeof(decimal)) || (t == typeof(double)) || (t == typeof(float)) || (t == typeof(byte)) || (t == typeof(bool))
  396. || (t == typeof(DateTime)) || (t == typeof(DateTime?)) || (t.IsEnum) || (t == typeof(long))||(t == typeof(Image)))
  397. {
  398. dict.Add(pi.Name, pi.GetValue(obj, null));
  399. }
  400. }
  401. return dict.SaveToFile(FileName, false);
  402. // return true;
  403. }
  404. /// <summary>
  405. /// 从本地载入对像的属性
  406. /// </summary>
  407. /// <param name="obj"></param>
  408. /// <param name="filename"></param>
  409. /// <returns></returns>
  410. public static bool DeSerializePropertys(object obj, string filename)
  411. {
  412. SerializeHash dict = SerializeHash.CreateFromFile(filename, false);
  413. if (dict == null) return false;
  414. PropertyInfo[] pis = obj.GetType().GetProperties();
  415. foreach (PropertyInfo pi in pis)
  416. {
  417. if (!pi.CanWrite) continue;
  418. if (pi.GetIndexParameters().Length > 0) continue;
  419. if (dict.ContainsKey(pi.Name))
  420. {
  421. try
  422. {
  423. pi.SetValue(obj, dict[pi.Name], null);
  424. }
  425. catch
  426. {
  427. }
  428. }
  429. }
  430. return true;
  431. }
  432. #endregion
  433. }

 

二、定义一个可序列话字典类

  1. /// <summary>
  2. /// 可序列化的字典类,要求包含对像也可序列化
  3. /// </summary>
  4. /// <typeparam name="TKey"></typeparam>
  5. /// <typeparam name="TValue"></typeparam>
  6. [Serializable()]
  7. public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
  8. {
  9. #region Constants
  10. private const string DictionaryNodeName = "Dictionary";
  11. private const string ItemNodeName = "Item";
  12. private const string KeyNodeName = "Key";
  13. private const string ValueNodeName = "Value";
  14. #endregion
  15. #region Constructors
  16. public SerializableDictionary()
  17. {
  18. }
  19. public SerializableDictionary(IDictionary<TKey, TVal> dictionary)
  20. : base(dictionary)
  21. {
  22. }
  23. public SerializableDictionary(IEqualityComparer<TKey> comparer)
  24. : base(comparer)
  25. {
  26. }
  27. public SerializableDictionary(int capacity)
  28. : base(capacity)
  29. {
  30. }
  31. public SerializableDictionary(IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer)
  32. : base(dictionary, comparer)
  33. {
  34. }
  35. public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
  36. : base(capacity, comparer)
  37. {
  38. }
  39. #endregion
  40. #region ISerializable Members
  41. protected SerializableDictionary(SerializationInfo info, StreamingContext context)
  42. {
  43. int itemCount = info.GetInt32("ItemCount");
  44. for (int i = 0; i < itemCount; i++)
  45. {
  46. KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<TKey, TVal>));
  47. this.Add(kvp.Key, kvp.Value);
  48. }
  49. }
  50. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  51. {
  52. info.AddValue("ItemCount", this.Count);
  53. int itemIdx = 0;
  54. foreach (KeyValuePair<TKey, TVal> kvp in this)
  55. {
  56. info.AddValue(String.Format("Item{0}", itemIdx), kvp, typeof(KeyValuePair<TKey, TVal>));
  57. itemIdx++;
  58. }
  59. }
  60. #endregion
  61. #region IXmlSerializable Members
  62. void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
  63. {
  64. //writer.WriteStartElement(DictionaryNodeName);
  65. foreach (KeyValuePair<TKey, TVal> kvp in this)
  66. {
  67. writer.WriteStartElement(ItemNodeName);
  68. writer.WriteStartElement(KeyNodeName);
  69. KeySerializer.Serialize(writer, kvp.Key);
  70. writer.WriteEndElement();
  71. writer.WriteStartElement(ValueNodeName);
  72. ValueSerializer.Serialize(writer, kvp.Value);
  73. writer.WriteEndElement();
  74. writer.WriteEndElement();
  75. }
  76. //writer.WriteEndElement();
  77. }
  78. void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
  79. {
  80. if (reader.IsEmptyElement)
  81. {
  82. return;
  83. }
  84. // Move past container
  85. if (!reader.Read())
  86. {
  87. throw new XmlException("Error in Deserialization of Dictionary");
  88. }
  89. //reader.ReadStartElement(DictionaryNodeName);
  90. while (reader.NodeType != XmlNodeType.EndElement)
  91. {
  92. reader.ReadStartElement(ItemNodeName);
  93. reader.ReadStartElement(KeyNodeName);
  94. TKey key = (TKey)KeySerializer.Deserialize(reader);
  95. reader.ReadEndElement();
  96. reader.ReadStartElement(ValueNodeName);
  97. TVal value = (TVal)ValueSerializer.Deserialize(reader);
  98. reader.ReadEndElement();
  99. reader.ReadEndElement();
  100. this.Add(key, value);
  101. reader.MoveToContent();
  102. }
  103. //reader.ReadEndElement();
  104. reader.ReadEndElement(); // Read End Element to close Read of containing node
  105. }
  106. System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
  107. {
  108. return null;
  109. }
  110. #endregion
  111. #region Private Properties
  112. protected XmlSerializer ValueSerializer
  113. {
  114. get
  115. {
  116. if (valueSerializer == null)
  117. {
  118. valueSerializer = new XmlSerializer(typeof(TVal));
  119. }
  120. return valueSerializer;
  121. }
  122. }
  123. private XmlSerializer KeySerializer
  124. {
  125. get
  126. {
  127. if (keySerializer == null)
  128. {
  129. keySerializer = new XmlSerializer(typeof(TKey));
  130. }
  131. return keySerializer;
  132. }
  133. }
  134. #endregion
  135. #region Private Members
  136. private XmlSerializer keySerializer = null;
  137. private XmlSerializer valueSerializer = null;
  138. #endregion
  139. public bool SaveToFile(string FileName, bool showException)
  140. {
  141. return SerializeHelper.XMLSerialize(this, FileName, showException);
  142. }
  143. }

三、定义可序列序列化实例类

  1. /// <summary>
  2. /// 可序列的哈希表,只能通过XML序列化
  3. /// </summary>
  4. [Serializable]
  5. public class SerializeHash : SerializableDictionary<string, object>
  6. {
  7. public SerializeHash()
  8. : base()
  9. {
  10. }
  11. public SerializeHash(IDictionary<string, object> dictionary)
  12. : base(dictionary)
  13. {
  14. }
  15. public SerializeHash(IEqualityComparer<string> comparer)
  16. : base(comparer)
  17. {
  18. }
  19. public SerializeHash(int capacity)
  20. : base(capacity)
  21. {
  22. }
  23. public SerializeHash(IDictionary<string, object> dictionary, IEqualityComparer<string> comparer)
  24. : base(dictionary, comparer)
  25. {
  26. }
  27. public SerializeHash(int capacity, IEqualityComparer<string> comparer)
  28. : base(capacity, comparer)
  29. {
  30. }
  31. protected SerializeHash(SerializationInfo info, StreamingContext context)
  32. {
  33. int itemCount = info.GetInt32("ItemCount");
  34. for (int i = 0; i < itemCount; i++)
  35. {
  36. KeyValuePair<string, object> kvp = (KeyValuePair<string, object>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<string, object>));
  37. this.Add(kvp.Key, kvp.Value);
  38. }
  39. }
  40. /// <summary>
  41. /// 将内含数据转为对应的类型
  42. /// </summary>
  43. /// <typeparam name="T"></typeparam>
  44. /// <param name="Name"></param>
  45. /// <param name="DefaultValue"></param>
  46. /// <returns></returns>
  47. public T GetObject<T>(string Name, T DefaultValue)
  48. {
  49. if (!this.ContainsKey(Name)) return DefaultValue;
  50. object obj = this[Name];
  51. if(!(obj is T)) return DefaultValue;
  52. return (T)obj;
  53. }
  54. public void SetObject(string Name, object Value)
  55. {
  56. if (this.ContainsKey(Name)) this[Name] = Value;
  57. else this.Add(Name, Value);
  58. }
  59. public static SerializeHash CreateFromFile(string FileName, bool showException)
  60. {
  61. return SerializeHelper.XMLDeSerialize<SerializeHash>(FileName, showException);
  62. }
  63. public bool SaveToFile(string FileName, bool showException)
  64. {
  65. return SerializeHelper.XMLSerialize(this, FileName, showException);
  66. }
  67. }

 

 四 使用实例:

  1. private static SerializeHash mSystemCachData;
  2. SystemCachData.SetObject("weburl", "www.baidu.com");
  3. if (mSystemCachData != null)
  4. {
  5. mSystemCachData.SaveToFile(System.IO.Path.Combine(Path, "DefaultData.xml"), false);
  6. }

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

闽ICP备14008679号