2

我正在尝试反序列化 c#3.5 中的 xml 字符串,下面的代码在 c# 4.0 中确实有效。当我尝试在 c#3.5 中的代码中运行Object reference not set to an instance of an object时,当代码尝试初始化 XmlSerializer 时出现异常。

任何帮助,将不胜感激。

string xml = "<boolean xmlns=\"http://schemas.microsoft.com/2003/10/serialization/\">false</boolean>";
var xSerializer = new XmlSerializer(typeof(bool), null, null,
             new XmlRootAttribute("boolean"),
             "http://schemas.microsoft.com/2003/10/serialization/");

             using (var sr = new StringReader(xml))
            using (var xr = XmlReader.Create(sr))
            {
                var y = xSerializer.Deserialize(xr);
            }

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="System.Xml"
  StackTrace:
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location, Evidence evidence)
       at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace)
       ....
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
4

1 回答 1

1

看起来在 .NET 3.5 中它不喜欢Type[] extraTypes为空。只需传递一个空Type[]值,例如new Type[0],或者只是简单地传递:

var xSerializer = new XmlSerializer(typeof(bool), null, Type.EmptyTypes, 
                 new XmlRootAttribute("boolean"),
                 "http://schemas.microsoft.com/2003/10/serialization/");

附带说明:当XmlSerializer使用非平凡的构造函数(比如这个)创建实例时,缓存和重用序列化程序非常重要- 否则它将为每个序列化程序生成一个内存中的程序集,这是一个:坏为了性能,但是 b: 导致严重的内存泄漏(无法卸载程序集)。

于 2012-11-14T11:03:40.290 回答