总结Unity知识归纳

数据类和字节数据转换

2017-04-07  本文已影响1人  IongX
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);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读