Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting the base part of a class

Status
Not open for further replies.

xwb

Programmer
Jul 11, 2002
6,828
GB
I've got two classes
Code:
class DeBase
{
   ...
}

class Derived: DeBase
{
   ...
}
DeBase can serialize, Derive cannot serialize (it has bits that I do not want to be serialized). Derived is stored in a tag of some UI control. I'm extracting it like
Code:
Derived ddd = (Derived) combo.tag;
If I just want the base part of Derived, in C++, I do something like
Code:
DeBase bbb = (DeBase) ddd;
but bbb is still Derived so when I try serializing, it fails. The only way I've found around it is
Code:
DeBase bbb = new DeBase();
bbb.something = ddd.something;
Problem is bbb is quite big and I don't really want to do individual assignments of every single member in it. Is there a more elegant way of doing this?
 
You could try declaring Derived as Serializable as well, and use the [NonSerialized] attribute on those fields that you do not want to be persisted.

Code:
[NonSerialized]
int value1;
That means value1 will not be serialized.

Otherwise, I think you can try to make some method in Derived that will serialize it's base class. Though I'm not entirely sure on this, you would have to use the 'base' keyword.

I hope that helps.

|| ABC
 
I was trying to avoid doing that (i.e. having to put [NonSerialized] in front of all the Derived classes. All I want to do is serialize the base class. Things that are so easy in C++ are an absolute minefield in C#.

I suppose the question is how do I do a deep copy in C# without having to assign each member. It seems to be doing shallow copies by default.
 
I did find a deep copy but it is a bit weird - it serializes the structure into a memory buffer and serializes out of it, boxing the result as the new type. The problem with this technique is that it doesn't go through the constructor.

This is a problem when debugging. I'm getting stuff constructed that doesn't go through the constructor.

It does, however, get round the serialization issue but a very roundabout technique.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top