xml serialization - C# Exception when trying to serialize a dynamic derived object -


i have following classes:

[xmlinclude(typeof(cat))] [xmlinclude(typeof(dog))] [xmlinclude(typeof(cow))] [serializable] public abstract class animal {     public string name { get; set; } }  public class cow : animal {     public cow(string name) { name = name; }     public cow() { } }  public class dog : animal {     public dog(string name) { name = name; }     public dog() { } }  public class cat : animal {     public cat(string name) { name = name; }     public cat() {} }  , following code snippet:   var animallist = new list<animal>(); type type = animaltypebuilder.compileresulttype("elephant", propertieslist); var elephant = activator.createinstance(type);  animallist.add(new dog()); animallist.add(new cat()); animallist.add(new cow()); animallist.add((animal)elephant);  using (var writer = new system.io.streamwriter(filename)) {      var serializer = new xmlserializer(animallist.gettype());      serializer.serialize(writer, animallist);      writer.flush(); } 

when try serilalize list "system.invalidoperationexception: type elephant not expected. use xmlinclude or soapinclude attribute specify types not known statically". @ first got exception cat, cow , dog objects , solved adding [xmlinclude(typeof())] classes seen above, can't find similar solution dynamic derived type since attribute set @ compile time..

you can tell xmlserializer types required via constructor @ run time. example:

var serializer = new xmlserializer(animallist.gettype(), new[] { typeof(elephant) }); 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -