I got a little problem with serializing object instance and let some pseudo code speak for itself:
List<A> ListOfA = new List<A>();
[Serializable]
public class A
{
public Object Instance;
...
}
[Serializable]
public class B
{
public String SomeAttribute = "example";
}
// This will be called:
void Serialize()
{
var a = new A();
a.Instance = new B();
ListOfA.Add(a);
// a.Instance = new String("test"); works but List<String>, B, ... throws Invalid Operation Exception when serializing:
using (TextWriter textWriter = new StreamWriter(filePath, false))
{
var xmlSerializer = new XmlSerializer(ListOfA.GetType());
xmlSerializer.Serialize(textWriter, ListOfA );
}
}
Anyone have a solution for this?
I have tried to use XmlInclude
without any result.
Is it even possible to serialize Object without knowing its type?
Try:
[XmlInclude(typeof(B))]
public class A {
public Object Instance;
}
Btw. [Serializable] is useless for xml serialization.
Thx for your fast response but I did find solution for my problem by giving second parameter to XmlSerializer:
var xmlSerializer = new XmlSerializer(ListOfA.GetType(), new Type[] { typeof(B) });
And this way I don't have to add [XmlInclude(typeof(B))] to class A...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.