码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-09-15 12:25:24      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

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[]

标签:

原文地址:http://www.cnblogs.com/Fefnir/p/5874557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!