二进制序列化
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Test : MonoBehaviour
{
void Start()
{
//SerilizeTest();
//DeSerilizeTest();
BinarySerilizeTest();
}
#region 二进制
/// <summary>
/// 初始化一个testSerilize,测试序列化二进制
/// </summary>
void BinarySerilizeTest()
{
TestSerilize testSerilize = new TestSerilize();
testSerilize.ID = 1;
testSerilize.Name = "二进制测试";
testSerilize.GradeList = new List<int>();
testSerilize.GradeList.Add(80);
testSerilize.GradeList.Add(90);
BinarySerilize(testSerilize);
}
void BinarySerilize(TestSerilize testSerilize)
{
//创建二进制文件流
FileStream fileStream = new FileStream(Application.dataPath + "/Test.bytes", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
//nameSpace:using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, testSerilize);
//流使用后一定要记得关闭,或者使用using(){}
fileStream.Close();
}
#endregion
}
找到Test.bytes文件后打开全是乱码
二进制反序列化
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class Test : MonoBehaviour
{
void Start()
{
//SerilizeTest();
//DeSerilizeTest();
//BinarySerilizeTest();
BinaryDeserilizeTest();
}
#region 二进制
/// <summary>
/// 初始化一个testSerilize,测试序列化二进制
/// </summary>
void BinarySerilizeTest()
{
TestSerilize testSerilize = new TestSerilize();
testSerilize.ID = 1;
testSerilize.Name = "二进制测试";
testSerilize.GradeList = new List<int>();
testSerilize.GradeList.Add(80);
testSerilize.GradeList.Add(90);
BinarySerilize(testSerilize);
}
void BinaryDeserilizeTest()
{
TestSerilize testSerilize = BinaryDeserilize();
Debug.Log("ID====" + testSerilize.ID);
Debug.Log("Name====" + testSerilize.Name);
foreach (int item in testSerilize.GradeList)
{
Debug.Log("Grade===" + item);
}
}
/// <summary>
/// 二进制序列化
/// </summary>
/// <param name="testSerilize"></param>
void BinarySerilize(TestSerilize testSerilize)
{
//创建二进制文件流
FileStream fileStream = new FileStream(Application.dataPath + "/Test.bytes", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
//nameSpace:using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, testSerilize);
//流使用后一定要记得关闭,或者使用using(){}
fileStream.Close();
}
/// <summary>
/// 二进制反序列化
/// </summary>
/// <returns></returns>
TestSerilize BinaryDeserilize()
{
TextAsset textAsset =UnityEditor.AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/test.bytes");
MemoryStream memoryStream = new MemoryStream(textAsset.bytes);
BinaryFormatter binaryFormatter = new BinaryFormatter();
TestSerilize testSerilize = (TestSerilize)binaryFormatter.Deserialize(memoryStream);
memoryStream.Close();
return testSerilize;
}
#endregion
}