C# 具有XmlTypeMapping和XmlRootAttribute参数的XmlSerializer构造函数
我想在C#中预取一组已知类类型的C# 具有XmlTypeMapping和XmlRootAttribute参数的XmlSerializer构造函数,c#,.net,xml,serialization,deserialization,C#,.net,Xml,Serialization,Deserialization,我想在C#中预取一组已知类类型的XmlTypeMapping,以加速它们的XML反序列化,同时将新的XmlSerializer实例化为XmlReflectionImporter.ImportTypeMapping(发生在类类型的XmlSerializer构造期间)这相当耗时,似乎发生在每个XmlSerializer构造中 此外,我正在解析的xml内容迫使我使用XmlRootAttribute参数设置要解析的xml根元素名称,因为它并不总是相同的。为了实现这一点,我可以使用XmlSerialize
XmlTypeMapping
,以加速它们的XML反序列化,同时将新的XmlSerializer
实例化为XmlReflectionImporter.ImportTypeMapping
(发生在类类型的XmlSerializer
构造期间)这相当耗时,似乎发生在每个XmlSerializer
构造中
此外,我正在解析的xml内容迫使我使用XmlRootAttribute
参数设置要解析的xml根元素名称,因为它并不总是相同的。为了实现这一点,我可以使用XmlSerializer(Type,XmlRootAttribute)
构造函数来反序列化我的对象
然而,我也希望从预取XmlTypeMapping
中获益,我看不到任何XmlSerializer
构造函数,比如:XmlSerializer(XmlTypeMapping,XmlRootAttribute)
或类似的东西。我怎样才能做到这一点
任何帮助都将不胜感激!谢谢。任何接受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))
{
}
}
公共类CachedRootXmlSerializer:XmlSerializer
{
私有静态字典rootMapCache=新字典();
私有静态XmlTypeMapping GetXmlTypeMappingFromRoot(类型类型,XmlRootAttribute XmlRootAttribute)
{
XmlTypeMapping结果=null;
int hash=17;
未经检查
{
hash=hash*31+type.GUID.GetHashCode();
hash=hash*31+xmlRootAttribute.GetHashCode();
}
锁(rootMapCache)
{
如果(!rootMapCache.ContainsKey(哈希))
{
XmlReflectionImporter importer=新的XmlReflectionImporter(null,null);
rootMapCache[hash]=importer.ImportTypeMapping(类型,xmlRootAttribute,null);
}
结果=rootMapCache[hash];
}
返回结果;
}
CachedRootXmlSerializer(类型类型,XmlRootAttribute XmlRootAttribute)
:base(GetXmlTypeMappingFromRoot(类型,xmlRootAttribute))
{
}
}
享受吧 该构造函数的另一个缺点是,它会将运行时生成的反序列化程序集保留在内存中,无法释放。谢谢,这真是太聪明了。:)