2

有以下结构

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

[Serializable]
public class Child : Parent
{
    public HashAlgorithm ha; //This is not Serializable

}

我想使用以下代码序列化它:

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();
    }
}

Child在我的代码中使用类型的对象,但是,我在Child对象中有一个不可序列化的字段(例如:HashAlgorithm)。Parent因此,我尝试使用以下代码转换为类型:

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

但是,这HashAlgorithm会返回不可序列化的错误,尽管尝试序列化不包含此字段的子项。我怎样才能完成我所需要的?

4

2 回答 2

4

这是不可能的。
您不能将一个类序列化为其基类之一。

相反,添加[NonSerialized]到该字段。

于 2011-01-30T03:55:01.520 回答
3

您可以在基类中实现 ISerializable ,然后从派生类中传递一些东西,例如:

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

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

实现 ISerializable 后,只需使用 Child 的 Serialize 方法。

于 2014-04-10T07:13:43.997 回答