using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Serialization
{
[Serializable]
class MSG
{
public int type;
public string message;
public MSG(int i, string s)
{
type = i;
message = s;
}
}
class Program
{
public static byte[] Serialization (MSG obj)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
byte[] msg = stream.ToArray();
return msg;
}
public static MSG DeSerialization (byte[] serializedAsBytes)
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
stream.Write(serializedAsBytes, 0, serializedAsBytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return (MSG)formatter.Deserialize(stream);
}
public static void Main(string[] args)
{
MSG msg = new MSG(1,"Я не сериализован");
byte[] buf = new byte[1024];
buf = Serialization(msg);
Console.WriteLine("До сериализации " + buf);
MSG msg1 = new MSG(2,"Текст");
msg1 = DeSerialization (buf);
Console.WriteLine("После сериализации " + msg1.message);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}