您好,登錄后才能下訂單哦!
這篇文章主要介紹了C#中序列化怎么實現(xiàn),具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
貼一下自己序列化的代碼:
public class XMLUtil { /// <summary> /// XML & Datacontract Serialize & Deserialize Helper /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serialObject"></param> /// <returns></returns> public static string Serializer<T>(T serialObject) where T : class { string result = string.Empty; using (MemoryStream mem = new MemoryStream()) { using (XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8)) { System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T)); ser.Serialize(writer, serialObject); result = Encoding.UTF8.GetString(mem.ToArray()); } } return result; } public static T Deserialize<T>(string str) where T : class { T result = null; using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(str))) { using (StreamReader streamReader = new StreamReader(memoryStream)) { System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); result = (T)xmlSerializer.Deserialize(memoryStream); } } return result; } }
上面的寫法持續(xù)序列化不會有內(nèi)存溢出的性能問題,之前一直被告知直接引用公司某位老鳥封裝好的dll來序列化,后來發(fā)現(xiàn)了老是出現(xiàn)內(nèi)存溢出,貼一下它的錯誤寫法,僅供吸取教訓(xùn):
public class XMLUtil { /// <summary> /// XML & Datacontract Serialize & Deserialize Helper /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serialObject"></param> /// <returns></returns> public static string Serializer<T>(T serialObject) where T : class { //try //{ XmlSerializer ser = new XmlSerializer(typeof(T)); System.IO.MemoryStream mem = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8); ser.Serialize(writer, serialObject); writer.Close(); return Encoding.UTF8.GetString(mem.ToArray()); //} //catch (Exception ex) //{ // return null; //} } public static T Deserialize<T>(string str) where T : class { //try //{ XmlSerializer mySerializer = new XmlSerializer(typeof(T)); StreamReader mem2 = new StreamReader( new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)), System.Text.Encoding.UTF8); return (T)mySerializer.Deserialize(mem2); //} //catch (Exception) //{ // return null; //} } //public static string Json_SerializeObject(object value) //{ // return Newtonsoft.Json.JsonConvert.SerializeObject(value); //} //public static object Json_DeserializeObject(string value) //{ // return Newtonsoft.Json.JsonConvert.DeserializeObject(value); //} //public static T Json_DeserializeObject<T>(string value) //{ // return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value); //} }
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C#中序列化怎么實現(xiàn)”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。