我正在尝试扩展一个框架。我正在扩展的类之一是序列化的。基类的GetObjectData()
方法未标记为虚拟,因此我无法覆盖它。
现在,如果对象在作为基类引用时被序列化,则它不是多态的,因此仅GetObjectData
调用基类'。
有没有办法在不修改基类的情况下将GetObjectData
其标记为虚拟?
[编辑] 我扩展了类并添加了一个我想要序列化的属性。以下问题的简单示例
[Serializable]
public class ParentClass : ISerializable
{
public float m_parent = 1.73f;
public ParentClass()
{ }
public ParentClass(SerializationInfo info, StreamingContext context)
{
Debug.Log("Loading parent");
m_parent = (float)info.GetValue("m_parent", typeof(float));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
Debug.Log("Saving parent");
info.AddValue("m_parent", m_parent, typeof(float));
}
}
[Serializable]
public class ChildClass : ParentClass
{
public int m_child = 73;
public ChildClass()
{ }
public ChildClass(SerializationInfo info, StreamingContext context) : base(info, context)
{
Debug.Log("Loading child");
m_child = (int)info.GetValue("m_child", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
Debug.Log("Saving child");
info.AddValue("m_child", m_child, typeof(int));
base.GetObjectData(info, context);
}
}
void Save()
{
Debug.Log("Starting save");
ParentClass aParent = new ChildClass() as ParentClass;
using (Stream stream = File.Open(fileName, FileMode.Create))
{
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, aParent);
}
Debug.Log("Save complete");
}
void Load()
{
Debug.Log("Starting load");
ChildClass aChild;
using (Stream stream = File.Open(fileName, FileMode.Open))
{
BinaryFormatter bFormatter = new BinaryFormatter();
aChild = bFormatter.Deserialize(stream) as ChildClass;
}
Debug.Log("Load complete" + aChild.m_child);
}
执行保存/加载会产生以下错误:
SerializationException: No element named m_child could be found.