2

为具有 ISerializable 字段的类实现 ISerializable 接口的正确方法是什么?

假设我有以下两个类,我必须为它们实现自定义序列化。我应该如何实现 Foo 的序列化/反序列化?

public class Foo : ISerializable
{
    private int b;

    private Bar bar;

    protected Foo(SerializationInfo info, StreamingContext context)
    {
        b = info.GetInt32("b") + 1000;
        // How should I instantiate "bar" field here?
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("b", b - 1000);
        // How should I serialize "bar" field here?
    }
}

public class Bar : ISerializable
{
    private int a;

    public Bar(SerializationInfo info, StreamingContext context)
    {
        a = info.GetInt32("a") + 100;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("a", a - 100);
    }
}
4

0 回答 0