Web Service 通过BinaryFormatter序列化和反序列化泛型List

来源:互联网 发布:淘宝店图片轮播制作 编辑:程序博客网 时间:2024/05/15 22:45
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<T>(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<T>(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())            {                List<Tb> list = conn.Query<Tb>(sql).ToList();                byte[] buffer = list.SerializeToByte();                return buffer;            }        }
4、调用Web Service并反序列化为List
private void BindData()        {            byte[] buffer = TestService.GetTbList(); //TestService为服务实例            List<Tb> list = buffer.ByteToDeserialize<List<Tb>>();            datagridview1.DataSource = list;                   }

原创粉丝点击