有以下结构
[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
会返回不可序列化的错误,尽管尝试序列化不包含此字段的子项。我怎样才能完成我所需要的?