I\'m refactoring my XML-serialization, and figured I\'d try the DataContractSerializer. Everything runs smoothly, until it needs to serialize this class:
You can also combine [KnownType] and reflection to make your code more resistant to future changes.
[DataContract]
[KnownType("GetKnownPersonTypes")]
internal class Person
{
private static IEnumerable _personTypes;
private static IEnumerable GetKnownTypes()
{
if (_personTypes == null)
_personTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof (Person).IsAssignableFrom(t))
.ToList();
return _personTypes;
}
}
Now a DataContractSerializer / DataContractJsonSerializer / XmlSerializer configured to work with Person, will also work with any type derived from Person (as long as it's declared within the same assembly).