具有以下结构
[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
不可序列化的错误。我怎样才能完成我需要的?
最佳答案
这是不可能的。
您不能将一个类序列化为其基类之一。
相反,将 [NonSerialized]
添加到该字段。
关于c# - 使用派生类的实例时如何序列化基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4841041/