[DataContract] [KnownType(typeof(Student))] [KnownType(typeof(Teacher))] public class Person { [DataMember] public string Name{get; set;} } //Serialize all derived types of Person. [DataContract] [KnownType("GetDerivedTypes")] public class Person { [DataMember] public string Name{get; set;} static IEnumerableGetDerivedTypes() { return from type in typeof(Person).Assembly.GetTypes() where typeof(Person).IsAssignableFrom(type) select type; } } [DataContract] public class Student: Person { [DataMember] public string Grade{get; set;} } [DataContract] public class Teacher : Person { [DataMember] public string Subject {get; set;} } public class MySerializer { var mySerializer = new DataContractSerializer(typeof(Person)); var stream = new MemoryStream(); var writter = new XMLTextWritter(stream, Encoding.UTF8) {Formatting = Formatting.Indented}; mySerializer.WriteObject(writter, new Teacher()); writter.flush(); Console.Writeline(stream); }
Saturday, July 20, 2013
Using KnownType in Serialization
Subscribe to:
Post Comments (Atom)
hi!,I really like your writing very so much!
ReplyDeleteMalwarebytes
Office 2017
Corel
Corel