更改类名称空间后无法反序列化 [英] Can't deserialize after changing class namespace

查看:156
本文介绍了更改类名称空间后无法反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有Seri​​alizable属性的类,并且在该类内是另一个被引用的类,该类也具有Seri​​alizable属性.现在,每当我尝试反序列化使用原始设计序列化的对象时,我都将引用的类移动到另一个名称空间,但抛出异常:System.Rutime.Serialization.TypeLoadExceptionHolder无法转换为类型"MyObjNamespace.MyObj".

这是我为解决此问题而编写的代码示例,但无法正常工作.有人可以告诉我我在做什么错吗?提前谢谢!

I have a class that has the Serializable attribute and within this class is another class that is referenced which also has the Serializable attribute. I moved the class that is reference into another namespace now whenever I try to deserialize objects that were serialized with the original design I throws the the exception: System.Rutime.Serialization.TypeLoadExceptionHolder cannot be converted to type "MyObjNamespace.MyObj".

Here''s an example of the code I''ve written to try to fix this but it''s not working. Can someone please tell what am I doing wrong here? Thanks in advance!

public class SerializationNamespaceConverter : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        typeName = typeName.Replace("oldNamespace, "newNamespace");
        return Type.GetType(typeName);
    }
}

BinaryFormatter biFrmtr = new BinaryFomatter();
biFrmtr.Bind = new SerializationNamespaceConverter();

List<MyObj> myObjs = (List<MyObj>) biFrmtr.Deserialize(myStream);

推荐答案

当然.向后移动代码名称空间或重新修改文件以修改文件中的名称空间.

您还能期待什么?一组可序列化类型描述的数据模型是一种契约,而声明的修改是违反契约的.

如果您确实需要一些明智的规定来促进数据模型的演进和备份兼容性,请使用阅读的数据合同:
http://msdn.microsoft.com/en-us/library/ms733127.aspx [ ^ ].

在这种方法中,作为合同组成部分的类或结构成员通过特殊属性进行了明显标记,这也使该方法成为最不介入的方法.另外,您可以(并建议)通过Namespace [DataContractAttribute]参数显式指定名称空间,该名称空间与.NET名称空间无关(我告诉过您,非介入式方法!).

请同时参阅我过去的答案:
如何在我的表单应用程序? [ ^ ],
创建属性文件... [反序列化json字符串数组 [
Of course. Either move the code namespace back or re-touch the files to modify namespace in the files.

What else can you expect? The data model described by the set of serializable type is a kind of contract, and modification of declarations is the violation of the contract.

If you really need some wise provisions for data model evolution and backup compatibility, use the read Data Contract:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

In this approach, the class or structure members which are parts of contract are clearly marked by the special attributes, which also makes this approach the most non-intrusive. Also, you can (and recommended) to specify namespaces explicitly by the Namespace [DataContractAttribute] parameter, unrelated to .NET namespaces (I told you, non-intrusive approach!).

Please see also my past answers:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deseralize a json string array[^].

—SA


这篇关于更改类名称空间后无法反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆