开发者

How can I serialize base class when working with instance of derived class?

开发者 https://www.devze.com 2023-02-07 06:02 出处:网络
Have the following structure [Serializable] public class Parent { public int x = 5; } [Serializable] public class Child : Parent

Have the following structure

[Serializable]
public class Parent
{
    public int x = 5;
}

[Serializable]
public class Child : Parent
{
    public HashAlgorithm ha; //This is not Ser开发者_JAVA技巧ializable

}

I want to serialize this using the following code:

public class Util {
    static public byte[] ObjectToByteArray(Object obj)
    {
        if (obj == null)
        {
            return null;
        }
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

I am working with objects of type Child in my code, however, I have a field within the Child object that is non-serializable (for example: HashAlgorithm). Hence, I attempted the convert to type Parent using the below code:

public byte[] tryToSerialize(Child c)
{
    Parent p = (Parent) c;
    byte[] b = Util.ObjectToByteArray(p);
    return b;
}

However, this returns the error that HashAlgorithm is not serializable, despite trying to serialize the child which does not include this field. How can I accomplish what I need?


This is not possible.
You cannot serialize a class as one of its base classes.

Instead, add [NonSerialized] to the field.


You can implement ISerializable in the base class and then just pass things from derived like:

private Child() { } // Make sure you got a public/protected one in Parent

private Child(SerializationInfo info, StreamingContext context) 
     : base(info, context) { }

After you implement ISerializable just use the Serialize method from Child.

0

精彩评论

暂无评论...
验证码 换一张
取 消