XmlSerializer
将对象序列化到 XML 文档中和从 XML 文档中反序列化对象,XML 序列化是将对象的公共属性 (Property) 和字段转换为序列格式(这里是指 XML)以便存储或传输的过程
防止内存泄露(摘自MSDN)
为了提高性能,XML 序列化基础结构动态生成程序集,以便对指定类型进行序列化和反序列化。该基础结构将找到并重新使用这些程序集。仅当使用以下构造函数时,才会发生此行为:
XmlSerializer(Type)
XmlSerializer(Type, String)
示例
namespace CSharpDemo { public class Test { public string Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] args) { Test t = new Test() { Id = "1", Name = "hello" }; string s = SerializeObj<Test>(t); Console.WriteLine(s); Test tt = (Test)DeserializeObj<Test>(s); Console.ReadLine(); } static T DeserializeObj<T>(string xml) { XmlSerializer xs = new XmlSerializer(typeof(T)); StringReader sr = new StringReader(xml); object obj = xs.Deserialize(sr); sr.Dispose(); return (T)obj; } static string SerializeObj<T>(T t) { XmlSerializer xs = new XmlSerializer(typeof(T)); StringWriter sw = new StringWriter(); xs.Serialize(sw, t); return sw.ToString(); } } }
更多详细介绍可以参考MSDN