Unity二进制序列化

二进制序列化

例:给需要序列化的类或属性添加标签

using System;
using System.Collections.Generic;
[Serializable]
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List PhoneNumber { get; set; }
}

主要代码

void BinarySerialization(User user)
{
    //文件流
    FileStream fileStream = new FileStream(Application.dataPath + "/test.bytes", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
    //新建二进制格式化程序
    BinaryFormatter bf = new BinaryFormatter();
    //序列化
    bf.Serialize(fileStream, user);
    fileStream.Dispose();
}   

反序列化

主要代码

User BinaryDeSerialization()
{
    //文件流
    FileStream fileStream = new FileStream(Application.dataPath + "/test.bytes", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    //新近二进制格式化程序
    BinaryFormatter bf = new BinaryFormatter();
    //反序列化
    User user =(User)bf.Deserialize(fileStream);
    fileStream.Dispose();
    return user;
}

你可能感兴趣的:(Unity二进制序列化)