I am converting a project so I can use Moq (Mock) testing.
I have a class which has a List of interfaces. I understand interfaces cannot be serialized. So I am trying to work around it.
I have created a console to test, however, after trying numerous methods from other SO posts ( Serializing a List hold an interface to XML, XmlSerializer serialize generic List of interface); I feel I need to ask for help.
The sample code below wraps the List in its own class so as to be able to implement ISerializable interface. However, I have the following summarized error:
Cannot serialize member MyConcreteCollection.ChildList of type IChild because
it is an interface.
The issue is in this code
public void WriteXml(System.Xml.XmlWriter writer)
{
//-- HAVE also tried IChild child in ChildList
foreach (ConcreteChild child in ChildList)
{
XmlSerializer s = new XmlSerializer(child .GetType());
s.Serialize(writer, child );
}
}
Here is the full code list. This is working and has fix implemented by user Jay
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
[Serializable]
public class ConcreteParent
{
public MyConcreteCollection MyConcreteCollection { get; set; }
}
[Serializable]
public class MyConcreteCollection : IXmlSerializable //(Was ISerializable, as fixed by user Jay)
{
public List<IChild> ChildList { get; set; }
public System.Xml.Schema.XmlSchema GetSchema() { return null; }
public void ReadXml(System.Xml.XmlReader reader) { }
public void GetObjectData(SerializationInfo info, StreamingContext context) { }
public void WriteXml(System.Xml.XmlWriter writer)
{
foreach (ConcreteChild child in ChildList)
{
XmlSerializer s = new XmlSerializer(child.GetType());
s.Serialize(writer, child);
}
}
}
public interface IChild { }
[Serializable] public class ConcreteChild : IChild { }
public static class SerializerHelper<T>
{
public static string Serialize(T myobject)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter stringWriter = new StringWriter();
xmlSerializer.Serialize(stringWriter, myobject);
string xml = stringWriter.ToString();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
return sw.ToString();
}
}
class Program
{
static void Main(string[] args)
{
try
{
ConcreteParent concreteParent = new ConcreteParent();
concreteParent.MyConcreteCollection = new MyConcreteCollection();
concreteParent.MyConcreteCollection.ChildList = new List<IChild>();
concreteParent.MyConcreteCollection.ChildList.Add(new ConcreteChild());
string xml = SerializerHelper<ConcreteParent>.Serialize(concreteParent);
Console.WriteLine(xml);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}