Create a Deep Copy in C#

后端 未结 8 2014
孤独总比滥情好
孤独总比滥情好 2020-12-04 01:48

I want to make a deep copy of an object so I could change the the new copy and still have the option to cancel my changes and get back the original object.

My proble

相关标签:
8条回答
  • 2020-12-04 02:12

    Another reason not to copy arbitrary objects: it is impossible to know, without examining the code behind an object, how that object will relate to other objects in the system, or whether certain values are magical. For example, two objects may both hold references to arrays that hold a single integer which equals five. Both of those arrays are used elsewhere in the program. What matter might not be that either array happens to hold the value five, but rather the effect that writing to the array may have on other program execution. There's no way a serializer whose author doesn't know what the arrays are used for will be able to preserve that relationship.

    0 讨论(0)
  • 2020-12-04 02:12

    Here is an elaboration of the answer by @schoetbi. You need to tell the class how to clone itself. C# does not distinguish between aggregation and composition and uses object references for both.

    If you had a class for storing information about a car, it could have instances fields, like engine, wheels, etc. (composition), but also manufacturer (aggregation). Both are stored as references.

    If you cloned the car, you would expect the engine and wheels to be cloned as well, but you certainly would not want the manufacturer to be cloned as well.

    0 讨论(0)
提交回复
热议问题