using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A01_SerializeAndDeserialize
{
[Serializable]//可序列化且不可被继承
class Person
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private int _Age;
public int Age
{
get { return _Age; }
set { _Age = value; }
}
public Person(string name, int age)
{
_Name = name;
_Age = age;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//序列化:将类的对象(字段以及数值),以文本的形式保存为文件。
//反序列化:创建相同的对象,然后将文本中的数值,重新赋值给对象的字段。
namespace A01_SerializeAndDeserialize
{
class Demo1
{
private string strFilePath = @"G:\TestSerialize.txt";
//序列化
public void Test1()
{
Person p = new Person("王俊凯",18);
if (File.Exists(strFilePath))
{
using (FileStream fs = new FileStream(strFilePath,FileMode.OpenOrCreate))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, p);
}
}
}
//反序列化
public void Test2()
{
Person p = null;
if (File.Exists(strFilePath))
{
using (FileStream fs = new FileStream(strFilePath, FileMode.OpenOrCreate))
{
BinaryFormatter bf = new BinaryFormatter();
p = bf.Deserialize(fs) as Person;
}
}
Console.WriteLine(p.Name);
Console.WriteLine(p.Age);
}
static void Main(string[] args)
{
Demo1 obj = new Demo1();
//obj.Test1();
obj.Test2();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace A01_SerializeAndDeserialize
{
[Serializable]//可序列化且不可被赋值
class Person
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private int _Age;
public int Age
{
get { return _Age; }
set { _Age = value; }
}
public Person(string name, int age)
{
_Name = name;
_Age = age;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
//序列化:将类的对象(字段以及数值),以文本的形式保存为文件。
//反序列化:创建相同的对象,然后将文本中的数值,重新赋值给对象的字段。
namespace A01_SerializeAndDeserialize
{
class Demo1
{
private string strFilePath = @"G:\TestSerialize.txt";
//序列化
public void Test1()
{
Person p = new Person("王俊凯",18);
if (File.Exists(strFilePath))
{
using (FileStream fs = new FileStream(strFilePath,FileMode.OpenOrCreate))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, p);
}
}
}
//反序列化
public void Test2()
{
Person p = null;
if (File.Exists(strFilePath))
{
using (FileStream fs = new FileStream(strFilePath, FileMode.OpenOrCreate))
{
BinaryFormatter bf = new BinaryFormatter();
p = bf.Deserialize(fs) as Person;
}
}
Console.WriteLine(p.Name);
Console.WriteLine(p.Age);
}
static void Main(string[] args)
{
Demo1 obj = new Demo1();
//obj.Test1();
obj.Test2();
}
}
}
test