1、序列化和反序列化的扩展方法如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization.Formatters.Binary;using System.IO;using System.Runtime.Serialization;public static class Extenstions { //序列化 public static byte[] SerializeToByte(this T o) { using (MemoryStream stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, o); byte[] buffer = stream.ToArray(); return buffer; } } //反序列化 public static T ByteToDeserialize (this byte[] buffer) { using (MemoryStream stream = new MemoryStream(buffer)) { IFormatter formatter = new BinaryFormatter(); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } }
2.为要序列化的类加上[Serializable]
[Serializable] public class Tb { public string Id { get; set; } public string Name { get; set; } }
3、Web Service 中序列化List
[WebMethod(Description = "")] public byte[] GetTbList() { string sql = "select * from tb"; using (var conn = Database.GetConn()) { Listlist = conn.Query (sql).ToList(); byte[] buffer = list.SerializeToByte(); return buffer; } }
4、调用Web Service并反序列化为List
private void BindData() { byte[] buffer = TestService.GetTbList(); //TestService为服务实例 Listlist = buffer.ByteToDeserialize
>(); datagridview1.DataSource = list; }