Unity中的序列化和反序列化
程序员文章站
2022-04-03 12:29:27
...
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Utils
{
public static class ObjectSerializationExtension
{
public static byte[] SerializeToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray) where T : class
{
if (byteArray == null)
{
return null;
}
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(byteArray, 0, byteArray.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = (T)binForm.Deserialize(memStream);
return obj;
}
}
}
}
上一篇: unity中如何反序列化xml进行读取
下一篇: layabox 3D物体位移