Convert instance of derived class to base class

Convert instance of derived class to base class

am 06.12.2007 15:22:39 von Oliver Weichhold

Note: I have posted this on microsoft.public.dotnet.xml with no response
after three days, so I have closed that thread and am trying here.

I have two classes:

public class BaseClass { ... }
public class DerivedClass : BaseClass { ... }

Suppose I have the following code:

DerivedClass dc = new DerivedClass();
BaseClass bc = (BaseClass)dc;

How can I serialize "bc" so that only the members of BaseClass are
serialized? Currently, it is doing this:


//DerivedClass members (including BaseClass members)


When what I want is this:


//BaseClass members only


Or to take a step back, I could accomplish this if I could convert my
instance of my derived class to my base class -- rather than just casting
the object as the base class, as .NET still sees the object as an instance
of the derived class.

Is this possible? If so, and you need more info in order to help further,
let me know what you need. I would prefer to be able to do this without
having to explicitly control the entire serialization process. But if
that's my only option, I may go about this a different way (i.e. copying
each member from derived class into new instance of base class).

Thanks in advance.

Jerad

Re: Convert instance of derived class to base class

am 07.12.2007 13:13:32 von Kevin Spencer

You would have to write your own conversion implementation to do this, but
yes, it is possible.

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP

"Jerad Rose" wrote in message
news:O4TH7NBOIHA.3556@TK2MSFTNGP03.phx.gbl...
> Note: I have posted this on microsoft.public.dotnet.xml with no response
> after three days, so I have closed that thread and am trying here.
>
> I have two classes:
>
> public class BaseClass { ... }
> public class DerivedClass : BaseClass { ... }
>
> Suppose I have the following code:
>
> DerivedClass dc = new DerivedClass();
> BaseClass bc = (BaseClass)dc;
>
> How can I serialize "bc" so that only the members of BaseClass are
> serialized? Currently, it is doing this:
>
>
> //DerivedClass members (including BaseClass members)
>

>
> When what I want is this:
>
>
> //BaseClass members only
>

>
> Or to take a step back, I could accomplish this if I could convert my
> instance of my derived class to my base class -- rather than just casting
> the object as the base class, as .NET still sees the object as an instance
> of the derived class.
>
> Is this possible? If so, and you need more info in order to help further,
> let me know what you need. I would prefer to be able to do this without
> having to explicitly control the entire serialization process. But if
> that's my only option, I may go about this a different way (i.e. copying
> each member from derived class into new instance of base class).
>
> Thanks in advance.
>
> Jerad
>