【问题标题】:deserialize a class whose assembly and namespace has changed反序列化程序集和命名空间已更改的类
【发布时间】:2012-03-01 00:52:30
【问题描述】:

我遇到了这里描述的问题:

http://social.msdn.microsoft.com/Forums/en-AU/csharplanguage/thread/b310c71a-2479-4a93-888a-29294cecbe09

他们使用 SerializationBinder 提供了一个解决方案。还有其他选择吗??就像用不同的命名空间和程序集装饰我的类一样?原因是我有一些有这个问题的类多次使用,我必须在代码的每一部分添加“formatter.Binder = ...”行。应用我假设的第二种解决方案会更容易。

谢谢。

【问题讨论】:

    标签: serialization namespaces assemblies


    【解决方案1】:

    如果程序集版本更改,序列化对象将变为无效。我曾经对Protobuf-Net 的源代码进行了更改以避免版本检查,并且这样做相当容易。但是,它可能会导致意外结果(数据最终出现在错误的字段中),除非您避免使用隐式字段,并使用注释手动为每个字段设置索引。这就是 Protobuf-Net 的优势,您可以控制序列化流中字段的顺序。

    另一种解决方案是使用custom serialization?比如:

    [Serializable]
    public class MyObject : ISerializable 
    {
      public int n1;
      public int n2;
      public String str;
    
      public MyObject()
      {
      }
    
      protected MyObject(SerializationInfo info, StreamingContext context)
      {
        n1 = info.GetInt32("i");
        n2 = info.GetInt32("j");
        str = info.GetString("k");
      }
    [SecurityPermissionAttribute(SecurityAction.Demand, 
    SerializationFormatter =true)]
    
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
      {
        info.AddValue("i", n1);
        info.AddValue("j", n2);
        info.AddValue("k", str);
      }
    }
    

    【讨论】:

    • 这是一种有效的方法,但活页夹更简单。感谢你的回答。我认为只有这两种可能。
    猜你喜欢
    • 2011-12-06
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多