序列化和反序列化
此文件在unity中实现
using UnityEngine;
using System.Collections;
using System;
[Serializable]//关键字 证明下面的类是可序列化的,在system的命名空间里
public class class1
{
public string Name;
public int Age;
}
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;//序列化和反序列化的头文件
public class classxuliehua : MonoBehaviour
{
public string Path = "E:\\dsfg.dat";
// Use this for initialization
void Start()
{
if (File.Exists(Path))
{
class1 nee = read();
Debug.Log(nee.Age + " " + nee.Name);
}
else
{
class1 cls = new class1();
cls.Age = 18;
cls.Name = "赵钱孙";
creat(cls);
}
}
void creat(class1 cls)
{
FileStream Fstream = new FileStream(Path, FileMode.Create);//开启一个流
BinaryFormatter Binary = new BinaryFormatter();//定义一个二进制的类
Binary.Serialize(Fstream, cls);//二进制序列化把序列化的文件写入流里
Fstream.Close();//关闭流
}
class1 read()
{
FileStream Fstream = new FileStream(Path, FileMode.Open);//开启流并打开路径文件
BinaryFormatter reserve = new BinaryFormatter();
class1 newclass = (class1)reserve.Deserialize(Fstream);//反序列化这个流,输入一个(object)文件
//Fstream.Close();
return newclass;
}
// Update is called once per frame
}