Witam podczas serializacji obiejtu dostaję wyjątek: "The type B was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.". Odnalezione matieruały do XmlInclude i SoapInclude nie rozwiązały problemu. Dopiero zakomentowana linijka z tworzeniem nowego obiektu prowadzi do prawidłowej serializacji obiektu, ale wydaje się to strasznie nadmiarowe i zapewne zbędne.
public class A
{
public string PropA { get; set; }
}
public class B : A
{
public string PropB { get; set; }
}
public class Obj
{
[System.Xml.Serialization.XmlElement(ElementName = "ObjA", Type = typeof(A))]
public A ObjA { get; set; }
public string Serialize()
{
// this.ObjA = new A() { PropA = this.ObjA.PropA };
var xSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Obj));
try
{
using (var mStream = new System.IO.MemoryStream())
{
using (var sWriter = new System.IO.StreamWriter(mStream))
{
xSerializer.Serialize(sWriter, this);
sWriter.Flush();
}
return System.Text.Encoding.UTF8.GetString(mStream.ToArray());
}
}
catch(Exception ex)
{
}
return string.Empty;
}
}
class Program
{
static void Main(string[] args)
{
Obj o = new Obj();
o.ObjA = new B() { PropB = "PropB" };
o.ObjA.PropA = "PropA";
string s = o.Serialize();
}
}