我需要使我的所有实体都可序列化。所以我在考虑 BaseEntity 中的 Backup 和 Restore 方法。但是在恢复过程中,我不能用保存的对象覆盖对象,因为 this 是只读的。
有任何解决方案或其他方法来获取可序列化实体吗?
我的代码:
internal class BaseEntity
{
private MemoryStream ms = new MemoryStream();
private BinaryFormatter bf = new BinaryFormatter();
public void Backup()
{
bf.Serialize(ms, this);
}
public void Restore()
{
this = (BaseEntity)bf.Deserialize(ms);
}
}
请您参考如下方法:
更常见的模式是不要让对象自己负责序列化/反序列化;相反,使用外部序列化程序:
var serializer = new DataContractJsonSerializer(typeof(YourClass));
var stream = ...;
YourClass yourObj = ...;
serializer.WriteObject(stream, yourObj);
var restoredObj = serializer.ReadObject(stream);
