I wrote some abstract class that support quick serialize and deserialize. I add StructLayout to the implementation class and i got crash ( without the StructLayout its working with no crash )
I have 2 question
- Is there is any better fest way to do the Serialize ( on this i do serialization in TotalMilliseconds = 0.4834 and using the standard way of .net i takes TotalMilliseconds = 2.120 ) ?
- Why the 'StructLayout' crash my code ( exception on the runtime at the start of the application running
{"Could not load type 'WindowsFormsApplication4.Element1' from assembly 'WindowsFormsApplication4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the format is invalid.":"WindowsFormsApplication4.Element1"}
The code
public abstract class SerializeElement
{
public abstract void Serialize(BinaryWriter bw);
public abstract void DeSerialize(BinaryReader br);
public sealed byte[] Serialize()
{
byte[] retVal = null;
using(MemoryStream ms = new MemoryStream())
{
using(BinaryWriter bw = new BinaryWriter(ms))
{
Serialize(bw);
retVal = ms.GetBuffer();
}
}
return retVal;
}
public sealed void DeSerialize()
{
byte[] retVal = null;
using(MemoryStream ms = new MemoryStream())
{
using(BinaryReader br = new BinaryReader(ms))
{
DeSerialize(br);
}
}
}
}
[StructLayout(LayoutKind.Sequential, Pack=4)]
public class Element1 : SerializeElement
{
public int Var1 { get; set; }
public int Var2 { get; set; }
public override void Serialize(BinaryWriter bw)
{
bw.Write(Var1);
bw.Write(Var2);
}
public override void DeSerialize(BinaryReader br)
{
Var1 = br.ReadInt32();
Var2 = br.ReadInt32();
}
}
static void Main()
{
Element1 e = new Element1()
{
Var1 = 1,
Var2 = 2
};
var tt = e.Serialize();