4

フレームワークを拡張しようとしています。私が拡張しているクラスの 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.

4

3 に答える 3

0

new 修飾子を使用して、基本クラスの実装をオーバーライドできます。


シリアライザーによって基本クラスによって参照されている場合、これは役に立ちません。newオーバーライドを機能させる には、子型として参照する必要があります。

この場合、唯一の希望は、1) シリアライゼーション ロジックを置き換えて制御できるようにすること、2) フレームワーク クラスに前後にマップされるシリアライゼーションの目的でプロキシ クラスを使用すること、3) フレームワークをフォークしてその制限を修正することです。または 4) 魔法

于 2015-06-09T20:47:51.680 に答える