美文网首页总结Unity知识归纳
数据类和字节数据转换

数据类和字节数据转换

作者: IongX | 来源:发表于2017-04-07 19:39 被阅读1次
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    
    public class DataSwitch
    {
    
        /// <summary>
        /// 数据类对象转成字节流
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ObjectToBytes(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 BytesToObject(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                IFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:数据类和字节数据转换

        本文链接:https://www.haomeiwen.com/subject/qhxkattx.html