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
In the second case you should consider using composition instead of inheritance eg
Base
or Derived
objects into a new adapter class that will only expose the required properties 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.