[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

microsoft.public.dotnet.framework

Serialising/Deserialising subclass to base class

Chris Ashley

6/20/2008 8:45:00 AM

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
1 Answer

Göran Andersson

6/20/2008 10:36:00 AM

0

Chris Ashley wrote:
> 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.

--
Göran Andersson
_____
http://www...