需要将序列化后的对象生产的txt文件放到项目文件下即bin/Debug,之后要添加项目引用,上一篇文章中类Person
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;
using 序列化;
/*引用同一个解决方案中其他项目的类
* 点击该项目,找到引用,右键点击添加引用,左侧点击项目,找到要用到的项目,确定
*/
namespace 反序列化
{
class Program
{
static void Main(string[] args)
{
//创建反序列化器
using (FileStream fs=new FileStream("1.txt",FileMode.Open,FileAccess.Read))
{
BinaryFormatter bf = new BinaryFormatter();
object obj=bf.Deserialize(fs);
Person p = obj as Person;//因为已经添加引用了,所以可以直接用
Console.WriteLine("{0},{1}",p.Name,p.Age);
Console.ReadKey();
}
}
}
}
本文介绍了一个使用 C# 进行反序列化的具体示例,通过 BinaryFormatter 类从一个文本文件中读取并还原序列化过的 Person 对象。
1357

被折叠的 条评论
为什么被折叠?



