Unity数据持久化 之 序列化C#类为2进制

本文仅作笔记学习和分享,不用做任何商业用途

本文包括但不限于unity官方手册,unity唐老狮等教程知识,如有不足还请斧正​​

Unity数据持久化 之 向文件流读写(详细Plus版)-CSDN博客

这篇文章让我十分恼火,因为写了很多代码却只存入了520 的int 变量和一个名为“字符串”的string变量,并且读取也很麻烦

那我问你,那我问你,那我问你,那我问你,如果存入一个有大量数据的类呢?

很简单,只需要一个官方写好的轮子即可 ---BinaryFormatter

命名空间

using System.Runtime.Serialization.Formatters.Binary;

使用(需要将你要存入的类加上特性[SeriaLizable]) 

 //2进制格式化程序 实例化一个类对象
 BinaryFormatter binaryFormatter = new BinaryFormatter();
 //序列化
 binaryFormatter.Serialize(fileStream, person);

 

 注意参数一的Stream并没有限定为FileStram,所以还有其他流?

1.用文件流序列化类

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class 练习题 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Person person = new Person();
        SaveClass(person);
    }
    //序列化类的方法
    public void SaveClass(Person person)
    {   //创建需要存储文件
        using (FileStream fileStream =new FileStream(Application.dataPath+"/FileName.json",FileMode.OpenOrCreate,FileAccess.Write))              
        {
            //2进制格式化程序 实例化一个类对象
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            //序列化
            binaryFormatter.Serialize(fileStream, person);
        }
    }
}

[Serializable]
public class Person
{
    public int id;
    public string name;
    public int age;
    public bool sex;
    public List<Person> list;
    public Dictionary<int, int> map = new Dictionary<int, int> { { 1,2},{ 3,4},{ 5,6} };
    Boys Boy1 = new Boys();


}
[Serializable]
public class Boys
{ 


}



2.内存流序列化类

 内存流序列化类的优点是可以在存入时就拿到要存储的字节流(字节数组)

  using (MemoryStream memoryStream = new MemoryStream())
  {
      //2进制格式化程序,实例化一个类对象
      BinaryFormatter binaryFormatter = new BinaryFormatter();
      //序列化类,将其存入memoryStream内存流中
      binaryFormatter.Serialize(memoryStream, person);
      //获取缓冲
      byte[] bytes = memoryStream.GetBuffer();
      //存入字节
      File.WriteAllBytes(Application.dataPath+"/FileName1.json", bytes);
  }

bytes可以作为网络传输的字节流

  • 12
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值