Serialization in Inherited Classes ?

G

Guest

I have a class inherited from Control, which I want to serialize, since
Control is not Serializable, I have had to implement ISerializable. This
works but I now want to inherit this base class into a number of other
classes, I was assuming that I could just mark them as [Serializable] and use
automatic serialization but this does not work (The new class cannot
deserialize, because it does not have the correct constructor ie one with
arguments (SerializationInfo info, StreamingContext context)). Am I being
stupid or do I need to use ISerializable on all descendent classes.
 
N

Nicholas Paldino [.NET/C# MVP]

Tony,

Unfortunately, once you choose to implement ISerializable in a base
class, every class that derives from that class needs to implement the
ISerializable interface as well as implement the serialization constructor
in order to support serialization.

Hope this helps.
 
A

at.

Hi Nicholas,

I saw your recent reply on microsoft.public.dotnet.languages.csharp
about custom serialization. I knew that "when you derive a new class
from one that implements ISerializable, the derived class must implement
both the constructor as well as the GetObjectData method if it has
variables that need to be serialized." (MSDN extract). But what's about
the opposite situation?

When a class B implements ISerializable and inherits from class A (which
doesn't implement ISerializable), how should I handle the
serialization/deserialization of the fields of the base class A?
Actually, before implementing ISerialible for class B, each class was in
charge of instantiating its own variable. Thus the constructor of B was
calling the constructor of A with the rights arguments. With B
implementing ISerializable, it is not possible anymore (it seems).

Any solution? Should B serialize all A fields in the GetObjectData
method and deserialize them in its special constructor?

Many thanks in advance for your advice!
Christian


Here is what I tried to do... But that doesn't work: A fields are not
(de)serialized
class A
{
public A(int i)
{ ... }
}

class B : A, ISerializable
{
public B(int i, int j) : base(i)
{ ... }

private B(SerializationInfo info, StreamingContext context)
{
j = info.GetInt32("j")
}


[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info,
StreamingContext context)
{
info.AddValue("j", j);
}
}


Nicholas Paldino [.NET/C# MVP] a écrit :
 

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