C# 序列化与反序列化
2016-05-26 09:51
459 查看
在C#网络编程中,为了传输复杂的数据类型,如类类型和容器,例如Dictionary,List。我们需要将其转换成字节数组。
C#中提供了序列化和反序列化来实现该方式。先转换成内存流,在转换成
序列化对象时,需要在类定义处加上[Serializable]。
例如: [Serializable] //序列化
public class Film
{}
C#中提供了序列化和反序列化来实现该方式。先转换成内存流,在转换成
public static System.IO.MemoryStream SerializeBinary(object request) { System.IO.MemoryStream memStream = new System.IO.MemoryStream(); serializer.Serialize(memStream, request); return memStream; } public static object DeSerializeBinary(System.IO.MemoryStream memStream) { object obj; obj = serializer.Deserialize(memStream); return obj; }
外层调用代码:
public void Send_Date(object obj) { TcpClient Ts = Ret_Client(); //获取TCP连接 NetworkStream nws = Ts.GetStream(); //获取网络流 System.IO.MemoryStream memStream = TypeChange.SerializeBinary(obj); byte[] byt = new byte[memStream.Length]; memStream.Read(byt, 0, byt.Length); nws.Write(byt, 0, byt.Length); } public object Receive_Date() { TcpClient Ts = Ret_Client(); NetworkStream nws = Ts.GetStream(); while (nws.DataAvailable) { byte[] byt = new byte[nws.Length]; //读取数据 nws.Read(byt, 0, byt.Length); memStream.Write(byt, 0, byt.Length); } return TypeChange.DeSerializeBinary(memStream); }
序列化对象时,需要在类定义处加上[Serializable]。
例如: [Serializable] //序列化
public class Film
{}
相关文章推荐
- C#中Dictionary类使用实例
- Dictionary扩展基础类向字典中添加键和值
- asp dictionary对象的用法
- C#如何遍历Dictionary
- C# Dictionary的使用实例代码
- RadioButtonList绑定图片及泛型Dictionary应用
- C#中Dictionary的作用及用法讲解
- C#实现自定义Dictionary类实例
- C#中Dictionary泛型集合7种常见的用法
- Python中dictionary items()系列函数的用法实例
- python中字典(Dictionary)用法实例详解
- o7_dictionary_accessibility的作用
- stardict 词典名
- python第七课词典
- NSDictionary
- A Better Way to Manage the Rails Secret Token
- JavaScript语法中的九个陷阱
- Oracle学习笔记1
- JavaScript中模拟 Dictionary键值对
- 黑马程序员---集合