建议57:实现ISerializable的子类型应负责父类的序列化我们将要实现的继承自ISerializable的类型Employee有一个父类Person,假设Person没有实现序列化,而现在子类Employee却需要满足序列化的场景。不过序列化器并没有默认处理Person类 ...
建议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(get='_blank'>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); } }
看见,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); } }
上面的例子中Person类未被设置成支持序列化。现在,假设Person类已经实现了ISerializable接口,那么这个问题处理起来会相对容易,在子类Employee中,我们只需要调用父类受保护的构造方法和GetObjectData方法就可以了。如下所示:
[Serializable] public class Person : ISerializable { public string Name { get; set; } public Person() { } protected Person(SerializationInfo info, StreamingContext context) { Name = info.GetString("Name"); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); } } [Serializable] public class Employee : Person, ISerializable { public int Salary { get; set; } public Employee() { } protected Employee(SerializationInfo info, StreamingContext context) : base(info, context) { Salary = info.GetInt32("Salary"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Salary", Salary); } }
原标题:编写高质量代码改善C#程序的157个建议——建议57:实现ISerializable的子类型应负责父类的序列化
关键词:C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。