zoukankan      html  css  js  c++  java
  • 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;           
            }
    
  • 相关阅读:
    [12.19模拟赛]矩形|扫描线+set
    网 络
    数组(二维)
    数组
    02-线程的三种创建方式
    01-线程(概念篇)
    IO流-文件操作
    Serializable 可串行化接口
    PrintStream 类
    ObjectIntputStream / ObjectOutputStream 类
  • 原文地址:https://www.cnblogs.com/gdjlc/p/3370018.html
Copyright © 2011-2022 走看看