首先定义一个person 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
[Serializable]
class PerSon
{
int age;
public int Age
{
get { return age; }
set { age = value; }
}
string name;
public string Name
{
get { return name; }
set { name = value; }
}
public PerSon(int age, string name)
{
this.age = age;
this.name = name;
}
}
}
在Main中代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace test
{
class Program
{
static void Main(string[] args)
{
PerSon ps=new PerSon (10,"小米"); // 先实例一个person类
// 将ps实例序列化
using (FileStream fs = new FileStream("bnt.bin", FileMode.OpenOrCreate))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(fs, ps);
}
// 将ps实例反序列化
using (FileStream fs = new FileStream("bnt.bin", FileMode.Open))
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
PerSon psnew= bf.Deserialize(fs) as PerSon;
System.Windows.Forms.MessageBox.Show(psnew.Age+" "+psnew.Name);//这里引用系统的ststem.window.Form程序集,点击引用找到就行了
}
}
}
}
序列化为了再程序关闭是时保存实例的数据, 上面重要得两点是 需要序列化的类要被[serializable] 和序列化类的名称 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter。
本文介绍了一个简单的C#程序实现Person类的对象序列化与反序列化过程。通过使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,文章展示了如何将包含年龄和姓名属性的Person对象保存到文件中,并在之后从该文件中读取并还原对象。
605

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



