我们可以通过给类添加Serializable特性,使其可以序列化与反序列化.通俗的说,就是能将这个类的对象信息保存到本地,也可以通过保存到本地的对象信息实例化对象.
首先,写一个Utils工具类来实现序列化与反序列化:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace ConsoleApplication1
{
class Utils
{
private BinaryFormatter bf;
public Utils ()
{
bf = new BinaryFormatter();
}
public void Serialize<T> (string path, T obj) where T: class
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
bf.Serialize(fs, obj);
fs.Close();
}
public T Deserialize<T>(string path) where T : class
{
if (!File.Exists (path))
{
Console.WriteLine("文件不存在: {0}", path);
return null;
}
FileStream fs = new FileStream(path, FileMode.Open);
T obj = bf.Deserialize(fs) as T;
fs.Close();
return obj;
}
}
}
写一个测试类Person:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
[Serializable]
class Person
{
private string flag;
public string Flag
{
get
{
return flag;
}
set
{
flag = value;
}
}
public string name;
}
}
测试:
#define debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = @"E:\Person.txt";
Person p = new Person();
p.name = "王二狗";
p.Flag = "大家好,我是flag";
Utils utils = new Utils();
utils.Serialize<Person>(path, p);
Person p2 = utils.Deserialize<Person>(path);
Console.WriteLine("p2.name: {0}, p2.Flag: {1}", p2.name, p2.Flag);
}
}
}
项目中用来存储进度信息蛮好用的.