Serialising/Deserialising subclass to base class

C

Chris Ashley

I have a class "RtpImage" which inherits from a class called
"LogImage". I serialise this class and then deserialise back to a
LogImage. However it seems that .NET is remembering its type and calls
the RtpImage constructor/finaliser instead of the LogImage constructor/
finaliser. This is causing me problems in the case of the finaliser.

I am serialising using this code:
public bool SaveToXML(string strLocation)
{
try
{
XmlSerializer mySerializer = new
XmlSerializer(typeof(LogImage));
StreamWriter myWriter = new StreamWriter(strLocation);
mySerializer.Serialize(myWriter, (LogImage)this);
myWriter.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}

I am deserialising using this code:

public static LogImage ImageInfoFromXML(string strInputXML)
{
LogImage imgNew;
XmlSerializer mySerializer = new
XmlSerializer(typeof(LogImage));
FileStream myFileStream = new FileStream(strInputXML,
FileMode.Open, FileAccess.Read, FileShare.Read);
imgNew = (LogImage)mySerializer.Deserialize(myFileStream);
return imgNew;
}

In both cases I am casting to LogImage, yet the resultant XML contains
a type attribute saying it is a serialised RtpImage, and when I
deserialise it is still an RtpImage despite my cast.

Is there any way around this apart from defining a copy constructor
for LogImage and creating a new instance before serialising, passing
it the RtpImage? Perhaps some kind of serialisation attribute I can
use on the classes?

Thanks,

Chris
 
G

Göran Andersson

Chris said:
I have a class "RtpImage" which inherits from a class called
"LogImage". I serialise this class and then deserialise back to a
LogImage. However it seems that .NET is remembering its type and calls
the RtpImage constructor/finaliser instead of the LogImage constructor/
finaliser.

You can only deserialise back to the same type that you serialised.
This is causing me problems in the case of the finaliser.
Why?

In both cases I am casting to LogImage, yet the resultant XML contains
a type attribute saying it is a serialised RtpImage, and when I
deserialise it is still an RtpImage despite my cast.

You are only casting the reference to the object, that doesn't change
the actual type of the object.
Is there any way around this apart from defining a copy constructor
for LogImage and creating a new instance before serialising, passing
it the RtpImage? Perhaps some kind of serialisation attribute I can
use on the classes?

No, if you want a LogImage object to be serialised, you need to have an
actual LogImage object.
 

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