序列化反序列化

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 序列化反序列化
{
class Program
{
static void Main(string[] args)
{
//需要将对象的状态保存起来 持久化
//序列化:将对象的状态持久化到某种设备上(磁盘)
//要将类标记为Serializable 这个类的对象才能被序列化
//以二进制的方式进行序列化,而不是文本文档

//反序列化:将之前序列化的文件还原为对象
#region[序列化]
Person p1 = new Person() { Age = 19, Name = "Rose" };
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (FileStream fs = new FileStream("se.bin", FileMode.Create))
{
bf.Serialize(fs, p1);
}
#endregion

#region【反序列化】
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf2 = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (FileStream fs = new FileStream("se.bin", FileMode.Open))
{
object obj = bf2.Deserialize(fs);
Person p3 = obj as Person;
Console.WriteLine("Age:" + p3.Age.ToString() + "Name:" + p3.Name);
}
#endregion


#region [将一个对象保存到文件文本中,用文件的方式让对象持久化,但是麻烦]
Person p = new Person();
if (File.Exists(@"1.txt"))
{
string[] strlines = File.ReadAllLines(@"1.txt");
p.Age = int.Parse(strlines[0]);
p.Name = strlines[1];
}
else
{
p.Age = 19;
p.Name = "Jack";
File.WriteAllLines(@"1.txt", new string[] { p.Age.ToString(), p.Name });
}
#endregion
Console.Read();
}

}
[Serializable]//表示这个对象可以被序列化,里面的成员如果有其它类,那么这个类也应该需要标记Serializable
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
}

原文地址:https://www.cnblogs.com/sumg/p/3743982.html