简体   繁体   中英

C# XmlSerializer can't serialize after casting member to System.Object

A simple struct:

public struct TestA
{
    public object value;
}

Create it and serialize it:

List<string> value = new List<string>();
value.Add("a1");
TestA a = new TestA();
a.value = value;

MemoryStream stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(a.GetType());
xml.Serialize(stream, a);

Can't be serialized, InvalidOperationException: The type of the argument object 'System.Collections.Generic.List' is not primitive.

If I change "public object value;" to "public List<string> value;" , it can be serialized.

I want to use this object value to store value with different types, so I make the type as object . Such as:

a.value = new List<int>();
a.value = 3;
a.value = "a string";

This ought to do the job.

[Serializable]
public class TestA : IXmlSerializable
{
    public object value;

    public XmlSchema GetSchema()
    {
        return (null);
    }

    public void ReadXml(XmlReader reader)
    {
        value = reader.ReadContentAsObject();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteValue(value);
    }
}

Thanks both code4life and Soham, I haven't tested your idea, because I found a very simple way. Give XmlSerializer the second paramter, give it the exact type of the object value .

XmlSerializer xml = new XmlSerializer(a.GetType(), new Type[] { typeof(List<string>) });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM