简体   繁体   English

从具有相同属性的另一个对象创建对象

[英]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. 我在C#中有一个对象,可以说20个属性,它是数据合成的一部分。 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? 除了将一个对象的每个属性分配给另一个对象的相应属性之外,有没有办法做到这一点?

是的,看看Automapper

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. 如果您使用的是2.0,那么反射可能就是您的朋友。 You can use HyperDescriptor to improve the performance if you need. 如果需要,您可以使用HyperDescriptor来提高性能。

如果您希望以自动方式执行反射,则可以选择反射,前提是属性名称可以在对象之间轻松映射。

Automapper is worth a try, but in the end, I decided it wasn't for me. Automapper值得一试,但最后,我认为它不适合我。 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. 你可以自由修改我提供的来源,我没有声称它的有效性,适用性,性能,你打破你保持零件等等,但它运作良好为我创建设计时对象到对象映射。

C#Object Clone Wars可能是一个很好的起点。

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

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