文件内存序列化和反序列化

/// <summary>
    /// 通用序列化器
    /// </summary>
    public class CommonSerialize
    {
        private static readonly IFormatter _formatter = new BinaryFormatter();

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data">数据流</param>
        /// <returns>对象</returns>
        public static object Deserialize(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
               return _formatter.Deserialize(stream);
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>数据流</returns>
        public static byte[] Serialize(object o)
        {
            using (var stream = new MemoryStream())
            {
                _formatter.Serialize(stream, o);
                return stream.ToArray();
            }           
        }
    }

 

posted on 2013-05-02 16:00  。!  阅读(494)  评论(0编辑  收藏  举报