次のような構造になっています
[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
このフィールドを含まない子をシリアル化しようとしたにもかかわらず、シリアル化できないエラーを返します。どうすれば必要なことを達成できますか?