十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章主要介绍了C#中序列化怎么实现,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
网站设计制作、成都网站设计服务团队是一支充满着热情的团队,执着、敏锐、追求更好,是创新互联的标准与要求,同时竭诚为客户提供服务是我们的理念。成都创新互联公司把每个网站当做一个产品来开发,精雕细琢,追求一名工匠心中的细致,我们更用心!
贴一下自己序列化的代码:
public class XMLUtil { ////// XML & Datacontract Serialize & Deserialize Helper /// ////// /// public static string Serializer (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 (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; } }
上面的写法持续序列化不会有内存溢出的性能问题,之前一直被告知直接引用公司某位老鸟封装好的dll来序列化,后来发现了老是出现内存溢出,贴一下它的错误写法,仅供吸取教训:
public class XMLUtil { ////// XML & Datacontract Serialize & Deserialize Helper /// ////// /// public static string Serializer (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 (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 (string value) //{ // return Newtonsoft.Json.JsonConvert.DeserializeObject (value); //} }
感谢你能够认真阅读完这篇文章,希望小编分享的“C#中序列化怎么实现”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!