Serialize a generic collection of interfaces?

S

Steven Nagy

XML serialising this class:

[Serializable]
public class Table
{
public List<IAction> Actions;
public List<Column> Columns;
}

I think the interface is the problem.
Something in my head tells me that it shouldn't be possible to
serialise the IAction.
Interfaces can't be declared with attributes.

EXCEPTION: System.InvalidOperationException
There was an error reflecting type 'TestProj.Table'

Any suggestions/workarounds ?
 
C

chanmm

Cast it to the data type that can be serialized. Perhaps encapsulate each
column with your own object and so.

chanmm
 
S

Steven Nagy

The columns weren't the problem.
Commenting out the IAction list did fix it.
So to get around the problem I had a base "action" object, and instead
of having my Actions implement the IACtion interface, they inherit from
the Action base object instead, which has a number of abstract methods.
The overall result is the same for me, but I would have preferred
interfaces.

For those viewing this solution in the future, you also need to include
an XmlInclude attribute on the actual base class indicating what
inheriting types are acceptable for serialization.
 
M

Markus Mayer

Steven Nagy, 26.12.2006 03:51:
The columns weren't the problem.
Commenting out the IAction list did fix it.
So to get around the problem I had a base "action" object, and instead
of having my Actions implement the IACtion interface, they inherit from
the Action base object instead, which has a number of abstract methods.
The overall result is the same for me, but I would have preferred
interfaces.

For those viewing this solution in the future, you also need to include
an XmlInclude attribute on the actual base class indicating what
inheriting types are acceptable for serialization.

Maybe I am wrong, but think about it the other way round: How would you
deserialize the data? Since you have nothing more than a collection of
interfaces, which class (implementing that interface) should be created?

You could go the hard way and de-/serialize your list by hand using
XmlWriter and XmlReader. I had to do this recently because I needed to
XMLize a private hashtable. It turned out to be a really bad idea. :)

However, with a bit of (Type).GetCustomAttributes(XmlWhateverAttribute,
true) and some coffee things worked fine. I wrote an article about the
technique to extract the XmlEnumAttribute from an enumeration member
some days ago. It is in german but the code should be easy to
understand. You can find it here: http://mac.defx.de/archiv/134

Regards,
Markus
 

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