C#中序列化的使用总结
程序员文章站
2022-03-31 21:10:17
...
贴一下自己序列化的代码:
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; } }
上面的写法持续序列化不会有内存溢出的性能问题,之前一直被告知直接引用公司某位老鸟封装好的dll来序列化,后来发现了老是出现内存溢出,贴一下它的错误写法,仅供吸取教训:
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); //} }
以上就是C#中序列化的使用总结的详细内容,更多请关注其它相关文章!
推荐阅读
-
Android onCreateOptionsMenu的使用方法总结
-
在android开发中尽量不要使用中文路径的问题详解
-
解析Android中实现滑动翻页之ViewFlipper的使用详解
-
基于Android中Webview使用自定义的javascript进行回调的问题详解
-
如何在IE10中使用ActiveX筛选功能将信任的网站设成例外
-
ZBrush布尔运算中的并运算怎么使用?
-
HTML5中indexedDB 数据库的使用实例
-
vue.js中toast用法及使用toast弹框的实例代码
-
windows系统中Python多版本与jupyter notebook使用虚拟环境的过程
-
php中curl、fsocket、file_get_content三个函数的使用比较