多态的实现序列化
转载:http://www.cnblogs.com/jiangfei5945/p/3483704.html
多态的实现序列化,乍一听有点蒙,其实就是序列化的时候序列化子类,反序列化的时候能多态的反序列化出子类来。
举例来说,下面的代码,定义了三个类ClassToSerialize是父类,ConcreteClassToSerializeA 和ConcreteClassToSerializeB 子类。
当我们序列化是序列化ConcreteClassToSerializeA,反序列化的时候我们希望反序列化出ConcreteClassToSerializeA对象,而不是ConcreteClassToSerializeB ,更不是ClassToSerialize。
[Serializable] [XmlInclude(typeof(ConcreteClassToSerializeA))] [XmlInclude(typeof(ConcreteClassToSerializeB))] public class ClassToSerialize { public string Name { get; set; } //public bool CanExecute(string name) //{ // return string.IsNullOrEmpty(name) ? false : true; //} } [Serializable] public class ConcreteClassToSerializeA : ClassToSerialize { public int Age { get; set; } } [Serializable] public class ConcreteClassToSerializeB : ClassToSerialize { public string Gender { get; set; } }
要想实现上述的需求,基类上必须添加[XmlInclude(typeof(ConcreteClassToSerializeB))]这样的属性。
public static void SerializeNow() { ConcreteClassToSerializeA c = new ConcreteClassToSerializeA(); c.Name = "asdf"; c.Age = 12; FileStream fileStream = new FileStream("e:\\temp1.txt", FileMode.Create); XmlSerializer b = new XmlSerializer(typeof(ClassToSerialize)); b.Serialize(fileStream, c); fileStream.Close(); } public static void DeSerializeNow() { object c = null; FileStream fileStream = new FileStream("e:\\temp1.txt", FileMode.Open, FileAccess.Read, FileShare.Read); XmlSerializer b = new XmlSerializer(typeof(ClassToSerialize)); c = b.Deserialize(fileStream); Console.WriteLine(c.ToString()); fileStream.Close(); }
注意XmlSerializer实例化的类型都是typeof(ClassToSerialize)。