XMLSerialize a class with members / properties that are interfaces

F

Fabian

I want to serialize a large tree structure of different objects to a xml
file. To get a loose coupling design some classes have interface members. At
runtime I get an InvalidOperationException: Cannot serialize member XYZ
because it is an interface.

To boil the thing down to a test example:

public interface IProblematicMember
{
}

public class ProblematicMember: IProblematicMember
{

}

public class DoesNotSerialize
{
private IProblematicMember problematicMember;

public IProblematicMember ProblematicMember
{
get { return problematicMember; }
set { problematicMember = value; }
}
}

class Program
{
static void Main(string[] args)
{
DoesNotSerialize dns = new DoesNotSerialize();
XmlSerializer mySerializer = new
XmlSerializer(typeof(DoesNotSerialize));
StreamWriter myWriter = new StreamWriter("myFileName.xml");
mySerializer.Serialize(myWriter, dns);
myWriter.Close();
}
}

Is there any possibility to solve this, e.g. by implementing the
serialization by hand?

Thanks for your help,

Fabian
 
F

Frans Bouma [C# MVP]

Fabian said:
I want to serialize a large tree structure of different objects to a
xml file. To get a loose coupling design some classes have interface
members. At runtime I get an InvalidOperationException: Cannot
serialize member XYZ because it is an interface.

To boil the thing down to a test example:

public interface IProblematicMember
{
}

public class ProblematicMember: IProblematicMember
{

}

public class DoesNotSerialize
{
private IProblematicMember problematicMember;

public IProblematicMember ProblematicMember
{
get { return problematicMember; }
set { problematicMember = value; }
}
}

class Program
{
static void Main(string[] args)
{
DoesNotSerialize dns = new DoesNotSerialize();
XmlSerializer mySerializer = new
XmlSerializer(typeof(DoesNotSerialize));
StreamWriter myWriter = new
StreamWriter("myFileName.xml");
mySerializer.Serialize(myWriter, dns); myWriter.Close();
}
}

Is there any possibility to solve this, e.g. by implementing the
serialization by hand?

You have to implement IXmlSerializable and indeed do the serialization
by hand.

FB


--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top