using System.Text; 2using System.IO; 3using System.Runtime.Serialization; 4 5 static string Serialize(object obj) 6 { 7 using (MemoryStream memoryStream = new MemoryStream()) 8 using (StreamReader reader = new StreamReader(memoryStream)) 9 { 10 DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); 11 serializer.WriteObject(memoryStream, obj); 12 memoryStream.Position = 0; 13 return reader.ReadToEnd(); 14 } 15 } 16 17 static object Deserialize(string xml, Type toType) 18 { 19 using (Stream stream = new MemoryStream()) 20 { 21 byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); 22 stream.Write(data, 0, data.Length); 23 stream.Position = 0; 24 DataContractSerializer deserializer = new DataContractSerializer(toType); 25 return deserializer.ReadObject(stream); 26 } 27 }