序列化、反序列化对象的用法

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
 
namespace MyProj.Base.Srv
{
    /// <summary>
    /// 处理数据 服务类
    /// </summary>
    public class BigDataBaseSrv
    {
        /// <summary>
        /// 读二进制数据,转换成相应的类型列表
        /// </summary>
        public List<T> ReadBytes<T>(byte[] argBytes) where T : class
        {
            List<T> list = null; //new List<T>();
            try
            {
                BinaryFormatter ser = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                ms.Write(argBytes, 0, argBytes.Length);
                ms.Position = 0;
                object obj = ser.Deserialize(ms);
                ms.Close();
                list = (List<T>)obj;
            }
            catch (Exception)
            {
            }
            return list;
        }
        /// <summary>
        /// 读二进制数据,转换成 字符串
        /// </summary>
        public string ReadBytes(byte[] argBytes)
        {
            string res = "";
            try
            {
                BinaryFormatter ser = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                ms.Write(argBytes, 0, argBytes.Length);
                ms.Position = 0;
                object obj = ser.Deserialize(ms);
                ms.Close();
                res = (string)obj;
            }
            catch (Exception)
            {
            }
            return res;
        }
        public byte[] SerializeList<T>(List<T> argList) where T : class
        {
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            ser.Serialize(ms, argList);
            byte[] buffer = ms.ToArray();
            ms.Close();
            return buffer;
        }
 
        public byte[] SerializeString(string argStr)
        {
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            ser.Serialize(ms, argStr);
            byte[] buffer = ms.ToArray();
            ms.Close();
            return buffer;
        }
    }
}
原文地址:https://www.cnblogs.com/jx270/p/4583699.html