Saturday, July 20, 2013

Using KnownType in Serialization

[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 IEnumerable GetDerivedTypes()
   {
       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);
   
}


1 comment: