技术开发 频道

可序列化对象的版本处理


【IT168技术文档】

  本章最后来看看可序列化对象的版本处理过程。为了理解为什么这是必须的,参考下面的例子。假定你建立了UserPrefs类(在本章开头时谈到过的)如下:
[Serializable] class UserPrefs { public string objVersion = "1.0"; public ConsoleColor BackgroundColor; public ConsoleColor ForegroundColor; public UserPrefs() { BackgroundColor = ConsoleColor.Black; ForegroundColor = ConsoleColor.Red; } }
  现在,假定有应用程序使用BinaryFormatter序列化该类的一个实例:
static void Main(string[] args) { UserPrefs up = new UserPrefs(); up.BackgroundColor = ConsoleColor.DarkBlue; up.ForegroundColor = ConsoleColor.White; // 将UserPrefs的一个实例保存为一个文件。 BinaryFormatter binFormat = new BinaryFormatter(); Stream fStream = new FileStream(@"C:\user.dat", FileMode.Create, FileAccess.Write, FileShare.None); binFormat.Serialize(fStream, up); fStream.Close(); Console.ReadLine(); }
0
相关文章