2011-09-29 28 views
7

我想在C#中預取,一組已知的類類型的XmlTypeMapping加快他們的XML序列化而實例化一個新XmlSerializerXmlReflectionImporter.ImportTypeMapping(在上課期間XmlSerializer敷設渠道發生類型)相當耗時,並且似乎在每個XmlSerializer構造中發生。與XmlTypeMapping和XmlRootAttribute參數XmlSerializer的構造

此外,我解析的xml內容迫使我使用XmlRootAttribute參數來設置xml根元素名稱解析,因爲它不總是相同的。爲了達到這個目的,我可以使用XmlSerializer(Type, XmlRootAttribute)構造函數來反序列化我的對象。

不過,我也想從預取XmlTypeMapping受益,我看不到任何XmlSerializer構造函數,如:XmlSerializer(XmlTypeMapping, XmlRootAttribute)或一些接近。我怎麼能做到這一點?

任何幫助將不勝感激!謝謝。

+1

該構造的另一個缺點是,它會保持一個運行時生成的解串器組件,內存無法釋放 – Aphelion

回答

3

內置緩存不用於任何接受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)) 
    { 
    } 
} 

享受!

+1

謝謝你,這是很聰明的。 :) – dletozeun