在使用XmlSerializer进行序列化或者反序列的时候,对于下面的两个构造方法

XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)

为了提高性能,XML 序列化基础结构将动态生成程序集,以序列化和反序列化指定类型。此基础结构将查找并重复使用这些程序集。

但是对于XmlSerializer(Type type, Type[] extraTypes) 等其他的构造函数,则会生成同一程序集的多个版本,且绝不会被卸载,这将导致内存泄漏和性能降低。

为了解决这个问题代码如下,仅供参考:

static Hashtable ht = new Hashtable();

        /// <summary>
/// 将指定的对象序列化为XML格式的字符串并返回。
/// </summary>
/// <param name="o">待序列化的对象</param>
/// <returns>返回序列化后的字符串</returns>
public static string Serialize(Object o, Type[] types = null)
{
if (o != null)
{ string xml = "";
XmlSerializer serializer = null;
try
{ if (types != null)
{
string names = "";
for (int i = 0; i < types.Length; i++)
{
names = names + types[i].FullName;
}
XmlSerializerFactory factory = new XmlSerializerFactory();
if (ht.ContainsKey(names))
{
serializer = (XmlSerializer)ht[names];
}
else
{
serializer = factory.CreateSerializer(o.GetType(), types);
ht.Add(names, serializer);
} // serializer = new XmlSerializer(o.GetType(), types);
}
else
{
serializer = new XmlSerializer(o.GetType());
} using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
XmlSerializerNamespaces n = new XmlSerializerNamespaces();
n.Add("", "");
serializer.Serialize(writer, o, n); mem.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(mem))
{
xml = reader.ReadToEnd();
}
}
}
types = null;
serializer = null;
}
catch { xml = ""; serializer = null; }
return xml;
}
else
{
return "";
}
}
04-15 17:32