文档介绍:回顾
对自定义类的对象排序,需要实现哪个接口?
比较两个对象使用哪个接口?
理解序列化/ 反序列化概念
能够使用序列化/反序列化保持和恢复对象状态
理解反射的概念
理解程序集的概念
本章目标
扩展配置信息
class Profile
{
public Profile() { }
//频道集合
public List<FeedBase> Feeds = new List<FeedBase>();
//...
//代理服务器信息
public bool EnableProxy;
public string ProxyName = null;
public string ProxyPort = null;
public string ProxyUserId = null;
public string ProxyUserPwd = null;
//系统语言
public UILanguage UILanguage;
}
修改Save和Load方法
//写入是否配置代理服务器
(());
//…写入增加的配置信息
1
2
//读入是否配置代理服务器
= (());
//读入代理服务器IP
= ()
修改保存配置信息的类
扩展的麻烦
添加更多的配置信息
需要编写大量重复繁琐的代码
每次增加配置信息都要修改
如何避免频繁的修改Save/Load方法?
神奇的方式
[Serializable]
abstract class FeedBase
存储信息的类都加入该标记
using ;
下面的类引入一个命名空间
Profile
FeedBase
RssFeed
AtomFeed
演示示例1 MyNewsReader
public void Save()
{
fileStream = new FileStream("", );
BinaryFormatter bf = new BinaryFormatter();
(fileStream, Profile);
();
}
public void Load()
{
fileStream = new FileStream("", );
BinaryFormatter bf = new BinaryFormatter();
Profile = (Profile)(fileStream);
();
}
修改Save和Load方法
这种方式称为序列化与反序列化
什么是序列化
Profile对象
界面语言:英语
RssFeed对象
存储
介质
存储
序列化是将对象的状态存储到特定存储介质中的过程
…
代理服务器
特性
[Serializable]
abstract class FeedBase
标识这个类是可序列化的
可序列化就是这个类的一个特性
描述性关键字
对程序中的元素如:类、字段、方法、属性
命名时以Attribute结尾: SerializableAttribute
使用时省略Attribute
public sealed class SerializableAttribute
特性其实是一个类
class Program
{
[Obsolete("不要使用旧的方法, 请使用新的方法", true)]
static void Old() { }
static void New() { }
public static void Main()
{
Old();
}
}
演示示例2 MyAttribute
使用序列化
fileStream = new FileStream("", );
BinaryFormatter bf = new BinaryFormatter();
(fileStream, Profile);
[Serializable]
abstract class FeedBase
要存储的对象标记为可序列化,包括他的父类和属性的类
使用二