Salary = 2000 };BinarySerializer.SerializeToFile(liming

时间:2022-02-07 07:50:09

建议57:实现ISerializable的子类型应卖力父类的序列化

我们将要实现的担任自ISerializable的类型Employee有一个父类Person,假设Person没有实现序列化,而此刻子类Employee却需要满足序列化的场景。不过序列化器并没有默认措置惩罚惩罚Person类型东西,这些工作只能由我们本身做。

以下是一个不妥的实现,序列化器只发明和措置惩罚惩罚了Employee中Salary字段:

class Program { static void Main() { Employee liming = new Employee() { Name = "liming", Salary = 2000 }; BinarySerializer.SerializeToFile(liming, @"c:\", "person.txt"); Employee limingCopy = BinarySerializer.DeserializeFromFile<Employee>(@"c:\person.txt"); Console.WriteLine(string.Format("姓名:{0}", limingCopy.Name)); Console.WriteLine(string.Format("薪水:{0}", limingCopy.Salary)); } } public class Person { public string Name { get; set; } } [Serializable] public class Employee : Person, ISerializable { public int Salary { get; set; } public Employee() { } protected Employee(SerializationInfo info, StreamingContext context) { Salary = info.GetInt32("Salary"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Salary", Salary); } }

序列化工具类:

public class BinarySerializer { //将类型序列化为字符串 public static string Serialize<T>(T t) { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, t); return System.Text.Encoding.UTF8.GetString(stream.ToArray()); } } //将类型序列化为文件 public static void SerializeToFile<T>(T t, string path, string fullName) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fullPath = Path.Combine(path, fullName); using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, t); stream.Flush(); } } //将字符串反序列化为类型 public static TResult Deserialize<TResult>(string s) where TResult : class { byte[] bs = System.Text.Encoding.UTF8.GetBytes(s); using (MemoryStream stream = new MemoryStream(bs)) { BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(stream) as TResult; } } //将文件反序列化为类型 public static TResult DeserializeFromFile<TResult>(string path) where TResult : class { using (FileStream stream = new FileStream(path, FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(stream) as TResult; } } }

View Code

输出为:

姓名:
薪水:2000

看见,,Name字段并没有正确措置惩罚惩罚。这需要我们改削类型Employee中受掩护的结构要领GetObjectData要领,为它插手父类字段的措置惩罚惩罚:

[Serializable] public class Employee : Person, ISerializable { public int Salary { get; set; } public Employee() { } protected Employee(SerializationInfo info, StreamingContext context) { Name = info.GetString("Name"); Salary = info.GetInt32("Salary"); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); info.AddValue("Salary", Salary); } }

改削后输出:

姓名:liming
薪水:2000