從具有相同屬性的另一個對象創建對象

[英]Creating objects from another object with same properties


I have an object in C# with lets say 20 properties and it's part of a datacontract. I also have another business entity with similar properties, which I want to populate from the response object. Is there any way to do this other than assigning each property of one object to the corresponding properties of the other?

我在C#中有一個對象,讓我們說20個屬性,它是datacontract的一部分。我還有另一個具有類似屬性的業務實體,我想從響應對象中填充它。除了將一個對象的每個屬性分配給另一個對象的相應屬性之外,有沒有辦法做到這一點?

5 个解决方案

#1


Yes, take a look at Automapper

是的,看看Automapper

#2


MiscUtil has an answer to this (PropertyCopy) that uses Expression (.NET 3.5) and a static field to cache the compiled delegate (so there is negligible cost per invoke):

MiscUtil有一個答案(PropertyCopy),它使用Expression(.NET 3.5)和一個靜態字段來緩存已編譯的委托(因此每次調用的成本可以忽略不計):

DestType clone = PropertyCopy<DestType>.CopyFrom(original);

If you are using 2.0, then probably reflection would be your friend. You can use HyperDescriptor to improve the performance if you need.

如果您使用2.0,那么反射可能是您的朋友。如果需要,可以使用HyperDescriptor來提高性能。

#3


Reflection is an option if you want to do it in an automated manner, provided the property names are easily mappable between the objects.

如果您希望以自動方式執行反射,則可以選擇反射,前提是屬性名稱可以在對象之間輕松映射。

#4


Automapper is worth a try, but in the end, I decided it wasn't for me. The big problem with those sorts of tools is you incur a great deal of runtime overhead each and every time a mapping occurs. I asked this same question last week and I ended up rolling my own solution (look at the accepted answer). You're free to modify the source I provided, I make no claims as to it's effectiveness, suitability, performance, you-break-it-you-get-to-keep-the-pieces, etc., but it works well enough for me to create design time object to object mapping.

Automapper值得一試,但最后,我認為它不適合我。這些工具的一個大問題是,每次映射發生時都會產生大量的運行時開銷。上周我問了同樣的問題,最后我推出了自己的解決方案(看看接受的答案)。你可以自由修改我提供的來源,我沒有聲稱它的有效性,適用性,性能,你打破它你保持片斷等等,但它運作良好為我創建設計時對象到對象映射。

#5


C# Object Clone Wars might be a good starting point.

C#Object Clone Wars可能是一個很好的起點。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/05/20/ca72b91a59d136cb5c674e7d6641dcee.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com