笨小孩做开发

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Dscf.Global.Utils
{
    public class ObjectUtils
    {
        /// <summary>
        /// 对像转成 byte 数组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToByte(Object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }
        /// <summary>
        /// 把序列化的数组转成对像
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Object ByteToObject(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                IFormatter formatter = new BinaryFormatter();
                Object obj = formatter.Deserialize(ms);
                return obj;
            }
        }
        /// <summary>
        /// 克隆一个对像
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static T CloneObject<T>(T t)
        {
            byte[] bb = ObjectToByte(t);
            object obj= ByteToObject(bb);
            return (T)obj;
        }
    }
}
posted on 2015-09-25 14:07  笨小孩做开发  阅读(228)  评论(0编辑  收藏  举报