反序列化错误 - 未设置对象引用

时间:2012-11-14 10:58:33

标签: c# deserialization

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

任何帮助都将不胜感激。

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: 

1 个答案:

答案 0 :(得分:1)

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

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

作为旁注:在使用非平凡构造函数(如此版本)创建XmlSerializer实例时,缓存并重新使用序列化程序非常重要 - 否则它' ll每个序列化器生成一个内存中的程序集,这是:性能不好,但b:导致严重的内存泄漏(无法卸载程序集)。