序列化與反序列化的簡便實用封裝 續

序列化與反序列化的簡便實用封裝 續

    之前寫過一篇有關.net中序列化與反序列化的文章,之後又幾次用到。但是當時沒有將其整個代碼放在我的博客中,後來朋友認爲這個代碼使用隨方便但是希望看到源碼,而自己又不知道這個是怎麼實現的,希望看到源碼。下面我就把這個序列化與凡序列化的源碼放在博客裏,滿足大家要求。
    很多朋友認爲這麼靈活的接口是不是實現起來很複雜,其實不然,很多時候越是抽象的代碼實現越是簡單。
using System;
using System.IO;
using System.Xml.Serialization;

namespace WriteResult.Common
{
   public class XMLManagement
   {
       private static XMLManagement insatnce = null;
       public static XMLManagement Create()
       {
            if (insatnce == null)
            {
                 insatnce = new XMLManagement();
            }
            return insatnce;
        }

       private XMLManagement() { }

       
public T Deserialize<T>(string xmlString)
       {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(xmlString);
            T entity = (T)(xs.Deserialize(reader));
            reader.Close();
            return entity;
        }

       
public string Serialize(object entity)
        {
             XmlSerializer xs = new XmlSerializer(entity.GetType());
             StringWriter writer = new StringWriter();
             xs.Serialize(writer, entity);
             string xmlString = writer.ToString();
             writer.Close();
             return xmlString;
         }
     }
}
其實源碼就這麼短,充其量就11行實現代碼,就算有單例模式也沒20行代碼量。希望大家能夠爲己所用。呵呵
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章