フレームワークを拡張しようとしています。私が拡張しているクラスの 1 つがシリアル化されています。基本クラスの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.