XmlSerializer Performance Issue when Specifying XmlRootAttribute

后端 未结 4 827
余生分开走
余生分开走 2020-12-01 08:17

I\'m currently having a really weird issue and I can\'t seem to figure out how to resolve it.

I\'ve got a fairly complex type which I\'m trying to serialize

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 08:42

    Just had to implement something like this and used a slightly more optimized version of @Dougc's solution with a convenience overload:

    public static class XmlSerializerCache {
        private static readonly Dictionary cache = new Dictionary();
    
        public static XmlSerializer Get(Type type, XmlRootAttribute root) {
            var key = String.Format("{0}:{1}", type, root.ElementName);
            XmlSerializer ser;
            if (!cache.TryGetValue(key, out ser)) {
                ser = new XmlSerializer(type, root);
                cache.Add(key, ser);
            }
            return ser;
        }
    
        public static XmlSerializer Get(Type type, string root) {
            return Get(type, new XmlRootAttribute(root));
        }
    }
    

提交回复
热议问题