简体   繁体   中英

Create new base class object from derived class object in C#

I've got an object of type Derived but want to have one of type Base . Normally, I can simply cast the object to a reference of Base . However, for my WCF service, I really want to expose the Base class only.

Is there a neat way to get the Base to a Derived object (or create a new Base from the Derived object) where the dynamic type is Base ?

Example:

myWcfResult.PropertyOfTypeBase = objectOfTypeDerived; // do some magic in this line
Assert.Trace(myWcfResult.PropertyOfTypeBase.GetType() == typeof(Base)); // should hold afterwards
// or at least WCF should be able to serialize it correctly into an XML element of type Base

If what you are trying to achieve is to hide the extra properties of the Derived class, then there are two options

  1. Either the consumer allows you to specify the type explicitly
  2. Or you have to change your design.

In the second case you should consider using composition instead of inheritance eg

  • Wrap the Base or Derived objects into a new adapter class that will only expose the required properties
  • Have the Base class as it is, but instead of adding the extra functionality by deriving from it, use composition: the Base class would contain another object that would define some aspects of the behaviour.

It is difficult to help you without a concrete example I am afraid.

If nothing else comes up I'm going to accept my own hackaround as solution: using AutoMapper to clone the Derived into a new Base :

Mapper.CreateMap<Base,Base>();
Mapper.Map<Base,Base>(objectOfTypeDerived);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM