Cómo agregar el atributo XmlInclude dinámicamente
Tengo las siguientes clases
[XmlRoot]
public class AList
{
public List<B> ListOfBs {get; set;}
}
public class B
{
public string BaseProperty {get; set;}
}
public class C : B
{
public string SomeProperty {get; set;}
}
public class Main
{
public static void Main(string[] args)
{
var aList = new AList();
aList.ListOfBs = new List<B>();
var c = new C { BaseProperty = "Base", SomeProperty = "Some" };
aList.ListOfBs.Add(c);
var type = typeof (AList);
var serializer = new XmlSerializer(type);
TextWriter w = new StringWriter();
serializer.Serialize(w, aList);
}
}
Ahora, cuando intento ejecutar el código, recibí una InvalidOperationException en la última línea que dice que
No se esperaba el tipo XmlTest.C. Utilice el atributo XmlInclude o SoapInclude para especificar tipos que no se conocen estáticamente.
Sé que agregar un atributo [XmlInclude (typeof (C))] con [XmlRoot] resolvería el problema. Pero quiero lograrlo dinámicamente. Porque en mi proyecto no se conoce la clase C antes de la carga. La clase C se está cargando como un complemento, por lo que no me es posible agregar el atributo XmlInclude allí.
Lo intenté también con
TypeDescriptor.AddAttributes(typeof(AList), new[] { new XmlIncludeAttribute(c.GetType()) });
antes de
var type = typeof (AList);
Pero no sirve de nada. Sigue dando la misma excepción.
¿Alguien tiene alguna idea sobre cómo lograrlo?