Object Serialization

S

Swappy

hi,

I have a class as MyClass & SecondClass which implement IMyInterface
interface.

class MyClass
{
Private SecondClass m_SecondClass;
}

Class SecondClass : IMyInterface
{

}

when i will run below code

MyClass Obj = new MyClass();
XmlSerializer serializer = new XmlSerializer(Obj.GetType());

Then while creating object of XmlSerializer it will give error of "There was
an Error Reflecting Type"

& the inner Exception will be " Interface cannot serialize"

The situation is like that I cannot eliminate interface.
How can i proceed to avoid that problem?
if possible PLZ suggest any other options.
 
M

Marc Gravell

First - it would *really* help if you posted realistic code.
Capitalization aside, to serialize with XmlSerializer types must be
public; and XmlSerializer only serializes public members (not private
members; ideally properties), so XmlSerializer won't do anything
unless there is a public member.

If that member is typed as SecondClass it will work fine; so I'm
guessing your property is typed as the interface. In which case you're
a bit scuppered. XmlSerializer can cope with derived classes via
XmlIncludeAttribute, but it can't handle interfaces. Consider a design
based around subclasses instead.

Marc
 
M

Marc Gravell

Here's a working example using base-classes:

using System;
using System.IO;
using System.Xml.Serialization;

static class Program
{
static void Main()
{
MyClass obj = new MyClass { SecondClass = new SecondClass
{ Foo = "abc" } };

using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xser = new XmlSerializer(typeof(MyClass));
xser.Serialize(ms, obj);
ms.Position = 0;
MyClass clone = (MyClass) xser.Deserialize(ms);
Console.WriteLine(((SecondClass)clone.SecondClass).Foo);
}
}
}

public class MyClass
{
private SomeBase m_SecondClass;
public SomeBase SecondClass
{
get { return m_SecondClass; }
set { m_SecondClass = value; }
}
}

public interface IMyInterface {}

[XmlInclude(typeof(SecondClass))]
public abstract class SomeBase : IMyInterface { }

public class SecondClass : SomeBase
{
public string Foo { get; set; }
}
 

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