【C#】Switch datatype between object and byte[]

时间:2022-03-31 07:12:39

This sample shows how to turn object to byte[], as well as turn byte[] to object.

So,I can turn any types of object into byte[],which can be saved and transported properly.

Attention!Attention!Attention!(Important things should be repeated three times:))

1.Don't forget to using <System.IO; System.Runtime.Serialization.Formatters.Binary; System.Runtime.Serialization;> at the beginning of your program.

2.When you need to transport an class/struct that defined by yourself, you'd better put the definition into a DLL file and using it in your program.

3.Also,put a [Serializable] before the definition(if it is defined on your own).

 public static byte[] Object2Bytes(object obj)
{
IFormatter fmt = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
fmt.Serialize(ms,obj);
return ms.GetBuffer();
} public static object Bytes2Object(byte[] bt)
{
IFormatter fmt = new BinaryFormatter();
MemoryStream ms = new MemoryStream(bt);
return (object)fmt.Deserialize(ms);
}