当前位置: 代码迷 >> Web前端 >> Web Service 透过BinaryFormatter序列化和反序列化泛型List
  详细解决方案

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

热度:491   发布时间:2013-10-16 11:29:46.0
Web Service 通过BinaryFormatter序列化和反序列化泛型List
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;           
        }

  相关解决方案