Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

theory - Why is cloning (in .NET) so difficult?

In the past I had the need to clone objects, only to find that they don't implement a Clone() method, forcing me to do it by hand (create a new instance and copy all properties from the original to the new one)

Why isn't cloning as easy as duplicating the memory block the object is allocated in, and thus have the Clone method in the object class, having all classes in .NET inherit it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because that wouldn't perform a deep clone, which is usually what clones really need to be. Imagine you have a reference to an array, or a list... simply copying the memory taken by your object will simply clone the reference. Any changes to the array will be visible through the clone as well as the original object - so the two objects are still connected, which violated the normal point of cloning.

If you want to implement exactly that functionality, it's easy - that's what Object.MemberwiseClone() is for. Most of the time, if it even makes sense to clone an object (what does a cloned NetworkStream mean?) it makes sense to clone each property... unless it refers to an immutable value already, etc. In other words, this is a naturally hard problem, which is why most types don't support cloning.

If you stick to immutable types wherever possible, it's not so much of an issue... that makes other things harder, admittedly, but it can be very powerful in many cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...