[英]Create new base class object from derived class object in C#
我有一個Derived
類型的對象,但想要一個Base
類型的對象。 通常,我可以簡單地將對象轉換為Base
的引用。 但是,對於我的WCF服務,我真的只想公開Base
類。
有沒有一種巧妙的方法可以將Base
轉換為動態類型為Base
的Derived
對象(或從Derived
對象創建新Base
)?
例:
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
如果您要實現的是隱藏Derived
類的額外屬性,則有兩個選擇
在第二種情況下,您應該考慮使用組合而不是繼承,例如
Base
對象或Derived
對象包裝到新的適配器類中,該類僅公開所需的屬性 恐怕沒有具體的例子就很難為您提供幫助。
如果沒有其他問題,我將接受自己的解決方法:使用AutoMapper將Derived
克隆到新的Base
:
Mapper.CreateMap<Base,Base>();
Mapper.Map<Base,Base>(objectOfTypeDerived);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.