內置緩存不用於任何接受XmlRootAttribute的構造函數。最好的辦法是使用接受單個XmlTypeMapping參數的構造函數:
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
而且將其包裝在自己的構造函數,它接受一個XmlRootAttribute,並使用XmlReflectionImporter從它構造XmlTypeMapping:
public class CachedRootXmlSerializer : XmlSerializer
{
private static Dictionary<int, XmlTypeMapping> rootMapCache = new Dictionary<int,XmlTypeMapping>();
private static XmlTypeMapping GetXmlTypeMappingFromRoot(Type type, XmlRootAttribute xmlRootAttribute)
{
XmlTypeMapping result = null;
int hash = 17;
unchecked
{
hash = hash * 31 + type.GUID.GetHashCode();
hash = hash * 31 + xmlRootAttribute.GetHashCode();
}
lock (rootMapCache)
{
if (!rootMapCache.ContainsKey(hash))
{
XmlReflectionImporter importer = new XmlReflectionImporter(null, null);
rootMapCache[hash] = importer.ImportTypeMapping(type, xmlRootAttribute, null);
}
result = rootMapCache[hash];
}
return result;
}
CachedRootXmlSerializer(Type type, XmlRootAttribute xmlRootAttribute)
: base(GetXmlTypeMappingFromRoot(type, xmlRootAttribute))
{
}
}
享受!
該構造的另一個缺點是,它會保持一個運行時生成的解串器組件,內存無法釋放 – Aphelion