Create a Deep Copy in C#

后端 未结 8 2141
孤独总比滥情好
孤独总比滥情好 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

    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.

提交回复
热议问题