简体   繁体   English

从C#中的派生类对象创建新的基类对象

[英]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转换为动态类型为BaseDerived对象(或从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类的额外属性,则有两个选择

  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 Base对象或Derived对象包装到新的适配器类中,该类仅公开所需的属性
  • 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 : 如果没有其他问题,我将接受自己的解决方法:使用AutoMapper将Derived克隆到新的Base

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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