C#Switch datatype between object and byte[]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#Switch datatype between object and byte[]相关的知识,希望对你有一定的参考价值。

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.

 

 1 public static byte[] Object2Bytes(object obj)
 2 {
 3     IFormatter fmt = new BinaryFormatter();
 4     MemoryStream ms = new MemoryStream();
 5     fmt.Serialize(ms,obj);
 6     return ms.GetBuffer();
 7 }
 8 
 9 public static object Bytes2Object(byte[] bt)
10 {
11     IFormatter fmt = new BinaryFormatter();
12     MemoryStream ms = new MemoryStream(bt);
13     return (object)fmt.Deserialize(ms);
14 }

 

以上是关于C#Switch datatype between object and byte[]的主要内容,如果未能解决你的问题,请参考以下文章

The Difference Between a Router, Switch and Hub

Switch between Server Core mode and Server GUI mode in Windows Server 2012 R2

错误:开关量不是整数开关((MPI_Datatype)数据类型)

autohotkey-GUISwitch between Windows of the Same Application

simplify the design of the hardware forming the interface between the processor and thememory system

C#Send data between applications