可序列化对象和byte[]数组之间的互转

        /// <summary>
        /// 将可序列化对象转成Byte数组
        /// </summary>
        /// <param name="obj">对象(对象不能为空)</param>
        /// <returns>返回相关数组</returns>
        protected static byte[] ObjectToByteArray<T>(T obj) where T : ISerializable
        {
            if (obj == null)
            {
                byte[] byteArr = new byte[] { };
                return byteArr;
            }
            else
            {
                MemoryStream ms = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, obj);
                ms.Close();
                return ms.ToArray();
            }
        }
        /// <summary>
        /// 将可序列化对象转成的byte数组还原为对象
        /// </summary>
        /// <param name="byteArry">byte数组</param>
        /// <returns>相关对象</returns>
        protected static T ByteArrayToObject<T>(byte[] byteArry) where T : ISerializable
        {
            if (byteArry != null && byteArry.Length > 0)
            {
                MemoryStream ms = new MemoryStream(byteArry);
                BinaryFormatter bf = new BinaryFormatter();
                return (T)bf.Deserialize(ms);
            }
            else
            {
                return default(T);
            }
        }

 

posted @ 2014-12-18 15:35  stevejson  阅读(7443)  评论(0编辑  收藏  举报