XML Serialize List of common objects obtained from the interface ,,

So, I'm trying to XML serialize a List<IObject> torn from an interface, but IObjects are common types ... the best thing to use is code:

 public interface IOSCMethod { string Name { get; } object Value { get; set; } Type Type { get; } } public class OSCMethod<T> : IOSCMethod { public string Name { get; set; } public T Value { get; set; } public Type Type { get { return _type; } } protected string _name; protected Type _type; public OSCMethod() { } // Explicit implementation of IFormField.Value object IOSCMethod.Value { get { return this.Value; } set { this.Value = (T)value; } } } 

And I have a list of IOSCMethods:

 List<IOSCMethod> 

of which I add objects as follows:

  List<IOSCMethod> methodList = new List<IOSCMethod>(); methodList.Add(new OSCMethod<float>() { Name = "/1/button1", Value = 0 }); methodList.Add(new OSCMethod<float[]>() { Name = "/1/array1", Value = new float[10] }); 

And this is the methodList that I am trying to serialize. But every time I try, I get "Can't serialize the interface", but when I create it (either IOSCMethod or OSCMethod<T> class), implement IXmlSerializable , I get the problem "cannot serialize an object with a constructor without parameters, but obviously I can't, because it's the interface! lame pants.

Any thoughts?

+4
source share
1 answer

Is this what you want:

 [TestFixture] public class SerializeOscTest { [Test] public void SerializeEmpTest() { var oscMethods = new List<OscMethod> { new OscMethod<float> {Value = 0f}, new OscMethod<float[]> {Value = new float[] {10,0}} }; string xmlString = oscMethods.GetXmlString(); } } public class OscMethod<T> : OscMethod { public T Value { get; set; } } [XmlInclude(typeof(OscMethod<float>)),XmlInclude(typeof(OscMethod<float[]>))] public abstract class OscMethod { } public static class Extenstion { public static string GetXmlString<T>(this T objectToSerialize) { XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType()); StringBuilder stringBuilder = new StringBuilder(); string xml; using (var xmlTextWriter = new XmlTextWriter(new StringWriter(stringBuilder))) { xmlSerializer.Serialize(xmlTextWriter, objectToSerialize); xml = stringBuilder.ToString(); } return xml; } } 
0
source

Source: https://habr.com/ru/post/1434615/


All Articles