序列化:序列化复杂类
public static string Serializer<T>(T obj) { MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(typeof(T)); try { //序列化对象 xml.Serialize(Stream, obj); } catch (InvalidOperationException) { throw; } Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; }
序列化:将流转换成XML字符串
public static XDocument Convert(Stream stream) { stream.Seek(0, SeekOrigin.Begin);//强制调整指针位置 using (XmlReader xr = XmlReader.Create(stream)) { return XDocument.Load(xr); } }
反序列化:
public static object Deserialize<T>(string xml) { try { using (StringReader sr = new StringReader(xml)) { XmlSerializer xmldes = new XmlSerializer(typeof(T)); return xmldes.Deserialize(sr); } } catch (Exception e) { return null; } }
反序列化:
public static object Deserialize<T>(Stream stream) { XmlSerializer xmldes = new XmlSerializer(typeof(T)); return xmldes.Deserialize(stream); }
时间: 2024-10-11 00:36:12