22

.NET 的反序列化错误非常普遍,例如:

System.ArgumentException:“System.Uri”类型的对象无法转换为“System.String”类型。

很明显,我们更改了对象中属性的类型,但是在这个序列化对象中大约有 10-15 个不同的类,所以很难弄清楚我们更改了哪个或者哪个提交搞砸了。

无论如何,是否可以获取有关哪个类(或至少在哪个类)中的哪个属性实际导致此错误的信息?是否有任何外部工具或已知方法可以做到这一点?

PS 在任何人开始告诉我为什么我不应该使用二进制序列化程序或为什么我应该使用 X、Y 等以实现向后兼容性之前,请保存关于这些的建议。我知道所有这些,但这不是问题。

4

3 回答 3

9

如果您启用对框架代码的调试(请参阅链接),然后按 ctrl + shift + e 并选择所有托管代码异常,则错误将出现在实际失败的源代码行中。然后,您应该能够使用堆栈跟踪来找出它当时试图反序列化的对象的哪一部分。

这并不容易,但这就是我们最终做到的方式。

于 2011-02-03T21:31:19.220 回答
1

There's a couple of different things you can do, none of them great. Especially with binary serialization. You could add custom serialization handling with the ISerializable interface, which would allow you to step through the deserialization process in the debugger.

Have you considered switching to Xml serialization for development/debugging purposes? There's a few more hooks that you can use with Xml serialization. But it sounds like that won't work for you, as you're probably dealing with either a remote interface or older binary data stored on disk that you need to read.

But even easier would be to look through your source control system's logs for the method with the changed type.

于 2011-02-03T21:24:10.133 回答
1

查看内部堆栈跟踪可能很有用。序列化程序生成一个专门用于处理您想要序列化/反序列化的类型的类。

只需查看堆栈跟踪中涉及的函数的函数名称,您就可以跟踪哪个节点节点正在破坏。

这有助于缩小问题所在的范围,尤其是对于大型复杂 XML 文件。

例子:

  at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Xml.XmlConvert.ToInt32(String s)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXML.Read13_Item(Boolean isNullable, Boolean checkType) //Tells you the issue is on the RootNodeSubNodeSubSubNode on an item withing it.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXML.Read17_RootNodeSubNodeSubSubNode(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXML.Read26_RootNodeSubNode(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXML.Read50_RootNode(Boolean isNullable, Boolean checkType)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXML.Read51_RootNode()
于 2013-11-15T10:54:06.363 回答