【转】C# 序列化与反序列化
2021-02-17 14:17
转自:https://www.cnblogs.com/lsy131479/p/8371858.html
对象持久化到文本文件,策略是:将对象的属性值打散,拆解,分别存储。
序列化:
保存对象的"全景图"
序列化是将对象转换为可保存或可传输的格式的过程
三种:
二进制序列器:
对象序列化之后是二进制形式的,通过BinaryFormatter类来实现的,这个类位于System.Runtime.Serialization.Formatters.Binary命名空间下
[Serializable] //使对象可序列化(必须添加)
特性
程序集,类,方法,属性都可以使用特性
Java中注解 C#特性
BinaryFormatter //创建二进制序列化器
Serialize(Stream(流),object(序列化对象))
流:可以理解成打通内存和硬盘的一个工具
输入流:从硬盘到内存
输出流:从内存到硬盘
XML序列化器:
对象序列化之后的结果符合SOAP协议,也就是可以通过SOAP?协议传输,通过System.Runtime.Serialization.Formatters.Soap命名空间下的SoapFormatter类来实现的。
SOAP序列化器:
对象序列化之后的结果是XML形式的,通过XmlSerializer?类来实现的,这个类位于System.Xml.Serialization命名空间下。XML序列化不能序列化私有数据。
反序列化:
将流转换为对象
Disk(硬盘)--->Cache(内存)
BinaryFormatter //创建二进制序列化器
Deserialize(Stream(流))//返回object类型
项目实例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Serializable_Deserialize
{
///
/// 用户类
///
//声明特性
[Serializable]
public class UserInfo
{
public UserInfo()
{
}
public UserInfo(string userName, string userAddress,string path)
{
UserName = userName;
UserAddress = userAddress;
Path = path;
}
public string UserName { get; set; }
public string UserAddress { get; set; }
public string Path { get; set; }
}
}

序列化:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Serializable_Deserialize
{
///
/// 序列化
///
class Program
{
static void Main(string[] args)
{
#region 序列化
//集合初始化器 初始化数据
List list = new List()
{
new UserInfo("房上的猫","北京海淀","https://www.cnblogs.com/lsy131479/"),
new UserInfo("倾城月光~淡如水","北京大兴","http://www.cnblogs.com/fl72/")
};
Console.WriteLine("二进制序列化中...");
//创建文件流派
Stream stream = new FileStream("save.bin", FileMode.Create);
//二进制序列化
BinaryFormatter bf = new BinaryFormatter();
//将对象或具有指定顶级 (根)、 对象图序列化到给定的流
bf.Serialize(stream, list);
//关闭流
stream.Close();
Console.WriteLine("二进制序列化成功!");
#endregion
Console.ReadLine();
}
}
}

反序列化:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Serializable_Deserialize
{
///
/// 反序列化
///
class Program
{
static void Main(string[] args)
{
#region 反序列化
//创建文件流派
Stream stream = new FileStream("save.bin", FileMode.Open);
//二进制序列化
BinaryFormatter bf = new BinaryFormatter();
//指定的流反序列化对象图
List list = (List)bf.Deserialize(stream);
//遍历反序列化后的泛型集合
foreach (UserInfo item in list)
{
Console.WriteLine(item.UserName + ":" + item.Path);
}
//关闭流
stream.Close();
#endregion
Console.ReadLine();
}
}
}
