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

本文介绍了一种通过扩展方法实现Web Service中泛型List的BinaryFormatter序列化和反序列化的方法。首先展示了序列化和反序列化的扩展方法,接着说明了需要为序列化的类添加[Serializable]特性,然后演示了在Web Service中如何序列化List对象并返回,最后给出了客户端如何调用Web Service并反序列化数据到List的示例。
摘要由CSDN通过智能技术生成
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;           
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值