c# - How to serialize a list of an interface? -
i got object has inherit general interface has list interface property.
going serialize follows problems, xmlserialzer not able determine real types inside of myclass.items
list elements.
using system; using system.collections.generic; using system.linq; using system.runtime.serialization; using system.text; using system.xml; using system.xml.serialization; namespace mytest { public interface imyinterface { string testproperty { get; set; } } public class myclass : imyinterface { public string testproperty { get; set; } public list<imyinterface> items { get; set; } } class program { static void main(string[] args) { myclass obj = new myclass() { testproperty = "test" }; xmlserializer xs = new xmlserializer(typeof(myclass)); // <- throws system.notsupportedexception using (xmlwriter xw = xmlwriter.create("file.xml", new xmlwritersettings() { encoding = encoding.utf8, indent = true, newlinehandling = newlinehandling.entitize })) { xs.serialize(xw, obj); } } } }
how can serialize list<t>
t interface?
unfortunately it's not supported out of box, it's doable. have use ixmlserializable
interface , write custom serialization. shouldn't difficult - you'd need enumerate through list, underlying type of each object , create new xmlserializer
type. deserialization bit more tricky, you'd need parse class names determine runtime types.
Comments
Post a Comment