c# - BinaryFormatter 在类更改后反序列化委托字段
问题描述
在 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 context) 在 System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder) 在 System.Runtime.Serialization.ObjectManager.DoFixups()
在 System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) 在 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler , Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) at ...我的代码中我反序列化的地方...
解决方案
我会考虑版本控制类,或者将您的传输与您的工作类分开。
所以你可能有一个 mySerializedClass 但然后有一个 myWorkingClass
包含委托。在序列化和反序列化时,您将在 mySerializedClass 中加载和保存 myWorkingClass。然后,您可以在应用程序获得新功能时快速执行诸如拥有不同版本的 mySerializedClass 之类的事情。
推荐阅读
- python-3.x - Python3:Process的子类,调用run()中的方法
- amazon-web-services - 永久更新 ecs 代理?
- r - R最小方差投资组合:求解不可逆矩阵
- firebase - 从缓存 Firebase 中获取数据是否抖动?
- javascript - 有没有办法改变 react-native-maps
无需重新渲染的 API 坐标? - sql - 如何使用 NodeJs 和带参数的 mssql 库插入 SQL
- javascript - 如何使用 JS 将页面滚动到底部?
- arrays - 从一个字符串 Swift 中拆分两个日期
- php - 散点融合图 - X 轴标签数据未完全显示 - PHP
- angular - gapi.client.youtube 在 Angular 应用程序中未定义