如何在C#中手动深度复制对象,以确保复制所有字段/属性?

huangapple go评论64阅读模式
英文:

When deep copying objects in C# by hand, how can you ensure that all the fields/properties are copied?

问题

我有一个包含20个基本字段和9个基本类型的列表/字典的类。这个类在性能关键的代码中使用,该代码利用了一个对象池。复制例程用于将状态从一个对象复制到从对象池中新租用的对象。该例程执行深复制,以确保列表/字典不会共享。

在调试过程中,我发现我在复制例程中漏掉了一个字段。我花了6个小时来追踪这个错误。

我该如何确保所有类字段都被正确复制,并且如果在添加新字段时未更新复制方法,则导致编译失败?或者是否有其他方法可以使复制例程更不容易出错?

我不能使用MemberwiseClone(),因为我不想分配内存。运行时反射不是一个选项,因为它可能会影响性能。我对序列化/反序列化也有类似的性能担忧(并且使用BinaryFormatter的最高投票SO方法现在已过时)。虽然手动复制是最快的选项,但它会使代码变得脆弱且难以维护。在这种情况下,提高代码可维护性的最佳方法是什么?

英文:

I have a class with 20 primitive fields and 9 Lists/Dictionaries of primitive types. This class is used in performance-critical code that utilizes an object pool. The copy routine is used to copy state from one object to a newly rented object from the object pool. The routine performs a deep copy to ensure that the Lists/Dictionaries are not shared.

While debugging, I found out that I had missed one of the fields in the copy routine. I spent 6 hours tracking down the error.

How can I ensure that all class fields are being copied correctly and fail compilation if the copy method is not updated when new fields are added? Or is there some other approach that would make the copy routine less brittle?

I can't use MemberwiseClone() because I don't want to allocate. Runtime reflection is not an option since it could hurt performance. I have similar performance concerns around Serialization/Deserialization (and the highest voted SO approach of using BinaryFormatter is now deprecated). While manual copying is the fastest option, it makes the code brittle and hard to maintain. What's the best approach to improve code maintainability in this scenario?

答案1

得分: 4

> 运行时反射不是一个选择,因为它可能会影响性能。
这可能对你的生产代码来说是一个限制,但我怀疑对于你的测试代码来说不是一个限制。

失败构建可能会很难实现 - 毫无疑问,使用Roslyn代码分析器可能是可行的,但至少有些棘手 - 但我期望编写一个单元测试应该相对简单,该测试会调用复制操作,然后使用反射比较结果。

英文:

> Runtime reflection is not an option since it could hurt performance.

That may well be a constraint for your production code, but I doubt that it's a constraint for your test code.

Failing the build may be hard to achieve - no doubt feasible with Roslyn code analyzers, but at least tricky - but I'd expect it to be relatively straightforward to write a unit test that invokes the copy operation and then compares the results using reflection.

huangapple
  • 本文由 发表于 2023年6月16日 01:17:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定