[英]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
. 我有一个
Derived
类型的对象,但想要一个Base
类型的对象。 Normally, I can simply cast the object to a reference of Base
. 通常,我可以简单地将对象转换为
Base
的引用。 However, for my WCF service, I really want to expose the Base
class only. 但是,对于我的WCF服务,我真的只想公开
Base
类。
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
? 有没有一种巧妙的方法可以将
Base
转换为动态类型为Base
的Derived
对象(或从Derived
对象创建新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 如果您要实现的是隐藏
Derived
类的额外属性,则有两个选择
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 Base
对象或Derived
对象包装到新的适配器类中,该类仅公开所需的属性 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
: 如果没有其他问题,我将接受自己的解决方法:使用AutoMapper将
Derived
克隆到新的Base
:
Mapper.CreateMap<Base,Base>();
Mapper.Map<Base,Base>(objectOfTypeDerived);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.