.NET XML Serialization and inheritance

前端 未结 6 502
别跟我提以往
别跟我提以往 2021-02-04 12:08

I have structure like this:

public interface A
{
    public void method();
}

public class B : A
{
}

public class C : A
{
}

List list;
6条回答
  •  遇见更好的自我
    2021-02-04 12:24

    I would use an abstract class instead of an interface (as one cannot serialize a type of interface), then instead of hard coding the type using the XmlInclude attribute, I would add the known types to the XmlSerializer in the Serial and Deserialize methods like so:

        string listXml = Serialize>(ListA, new Type[] { typeof(B), typeof(C) });
    
        List NewList = Deserialize>(listXml, new Type[] { typeof(B), typeof(C) });
    
        private static T Deserialize(string Xml, Type[] KnownTypes)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T),KnownTypes);
    
            StringReader sr = new StringReader(Xml);
            return (T)xs.Deserialize(sr);
        }
    
        private static string Serialize(Object obj, Type[] KnownTypes)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T), KnownTypes);
    
                xs.Serialize(sw, obj);
            }
            return sb.ToString();
        }
    

提交回复
热议问题