I'd like to prefetch in C#, the XmlTypeMapping
of a known set of class types to speed up XML deserialization of them while instantiating a new XmlSerializer
as XmlReflectionImporter.ImportTypeMapping
(happening during XmlSerializer
contruction on a class type) is quite time consuming and seem to happen at each XmlSerializer
construction.
我想在c#中预取,c#是已知的一组类类型的XmlTypeMapping,在实例化一个新的XmlSerializer为XmlReflectionImporter的同时,加速它们的XML反序列化。ImportTypeMapping(发生在类类型上的XmlSerializer构造期间)非常耗时,并且似乎在每个XmlSerializer构造中都发生过。
In addition the xml content I am parsing forces me to use XmlRootAttribute
argument to set the xml root element name to parse as it is not always the same. To achieve that, I can use the XmlSerializer(Type, XmlRootAttribute)
constructor to deserialize my object.
此外,我正在解析的xml内容迫使我使用XmlRootAttribute设置xml根元素名称以进行解析,因为它并不总是相同的。为此,我可以使用XmlSerializer(类型,XmlRootAttribute)构造函数来反序列化我的对象。
However I would also like to benefit from the prefetch XmlTypeMapping
and I can't see any XmlSerializer
constructor like : XmlSerializer( XmlTypeMapping, XmlRootAttribute )
or something close. How could I achieve that?
但是,我也想从prefetch XmlTypeMapping中获益,我看不到任何XmlSerializer构造函数,比如:XmlSerializer(XmlTypeMapping, XmlRootAttribute)或类似的东西。我怎么能做到呢?
Any help would be greatly appreciated! Thanks.
如有任何帮助,我们将不胜感激!谢谢。
3
The built-in cache is not used on any of the constructors that accept an XmlRootAttribute. Your best bet is to use the constructor that accepts a single XmlTypeMapping parameter:
内置缓存不用于接受XmlRootAttribute的任何构造函数。最好的方法是使用接受单个XmlTypeMapping参数的构造函数:
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
And to wrap it in your own constructor that accepts a XmlRootAttribute, and constructs the XmlTypeMapping from it using XmlReflectionImporter:
要将它封装到接受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))
{
}
}
Enjoy!
享受吧!
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2011/09/29/14739aa4518375b462d7a0a1932ce0ae.html。