需要序列化和反序列化时:1)在需要序列化的类顶部加上[Serializable]特性;
2)引用using System.Runtime.Serialization.Formatters.Binary;
namespace MySerializable
{
[Serializable]
public class Student
{
public Student() { }
public Student(string name, int age, string hobby)
{
this.Name = name;
this.Age = age;
this.Hobby = hobby;
}
/// <summary>
/// 姓名
/// </summary>
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// 年龄
/// </summary>
private int age;
public int Age
{
get { return age; }
set
{
//属性是聪明的字段
if (value > 0 && value < 100)
{
age = value;
}
else
{
age = 18;
}
}
}
/// <summary>
/// 爱好
/// </summary>
private string hobby;
public string Hobby
{
get { return hobby; }
set { hobby = value; }
}
}
}
序列化和反序列化的方法如下:
using System;
using System.Collections.Generic;
using System.Text;
//引入命名空间
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace MySerializable
{
public class Program
{
static void Main(string[] args)
{
Student student = new Student();
student.Name = "张三";
student.Age = 23;
student.Hobby = "足球,篮球,排球";
//序列化
ObjectSerializable(student, "E://Student.bin");
//反序列化
string str = ObjectUnSerializable("E://Student.bin").ToString();
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="obj"></param>
/// <param name="filePath"></param>
private static void ObjectSerializable(object obj, string filePath)
{
//定义文件流
FileStream fs = null;
try
{
fs = new FileStream(filePath, FileMode.Create);
//二进制方式
BinaryFormatter bf = new BinaryFormatter();
//序列化存储对象
bf.Serialize(fs, obj);
}
catch (IOException ex)
{
Console.WriteLine("序列化是出错!");
}
finally
{
if (fs != null)
{
//关闭文件流
fs.Close();
}
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static object ObjectUnSerializable(string filePath)
{
FileStream fs = null;
object obj = null;
try
{
fs = new FileStream(filePath, FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
obj = bf.Deserialize(fs);
}
catch (IOException ex)
{
Console.WriteLine("反序列化时出错!");
}
finally
{
if (fs != null)
{
fs.Close();
}
}
return obj;
}
}
}