类更改后,BinaryFormatter反序列化委托字段

时间:2019-01-04 17:14:15

标签: c# .net deserialization binaryformatter binary-serialization

我在C#中使用BinaryFormatter,试图从包含委托属性的类中反序列化对象。

在委托引用的类上添加成员后,反序列化中断。  参见下面的示例。

即使我完全忽略有问题的委托属性,我也需要反序列化才能工作。 例如,如果委托属性始终反序列化为null,则将解决此问题。 我无法通过将属性标记为[NonSerialized]或将其更改为字段来解决它。

以下内容将介绍我要反序列化的序列化对象。

public class mySerializedClass
{
    public string thisIsOK1 {get; set;}
    public string thisIsOK2 {get; set;}
    public Func<myModelClass,bool> thisIsTheIssue {get; set;}
}

[Serializable]
public class myModelClass
{
    // The issue happened after adding a new method to this class

    public static bool testMethod(mySerializedClass obj)
    {
        // do stuff
        return true
    }
}

作为序列化实例的示例:

new mySerializedClass()
{
    thisIsOK1 = "a";
    thisIsOK2 = "b";
    thisIsTheIssue = (o) => myModelClass.testMethod(o);    
}

有效的解决方案是始终将“ thisIsTheIssue”属性序列化/反序列化为null。

作为附加信息,异常消息为:

  

无法获取成员'get_theNameOfMyDelegate b__19_0'。

并且异常的StackTrace是:

  在

  System.Reflection.MemberInfoSerializationHolder.GetRealObject(StreamingContext   上下文)   System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder   持有人)在System.Runtime.Serialization.ObjectManager.DoFixups()
  在   System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler   处理程序,__ BinaryParser serParser,布尔值fCheck,布尔值   isCrossAppDomain,IMethodCallMessage methodCallMessage)   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(流   serializationStream,HeaderHandler处理程序,布尔值fCheck,布尔值   isCrossAppDomain,IMethodCallMessage methodCallMessage)   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(流   serializationStream)在...我的代码中反序列化的位置...

1 个答案:

答案 0 :(得分:0)

我会考虑版本控制类,或者将您的传输与工作类分开。

所以您可能有一个mySerializedClass,但是又有一个myWorkingClass

包含委托。在进行序列化和反序列化时,您将在mySerializedClass中加载和保存myWorkingClass。然后,您可以在其中进行快速的操作,例如在应用程序具有新功能时使用不同版本的mySerializedClass。

相关问题