开发者

Copy C# object along with reference [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 10 years ago.

Possible Duplicate:

Cloning objects in C#

I have an object created in c# say Object1. I need to temporarily back up this object to another object say ObjectOriginal.

However if I do ObjectOriginal = Object1, any changes to Object 1 affect ObjectOriginal. How do I go about this?


It all depends on what Object1 actually is, i.e. is it a DataTable, a String, or something else entirely?

By writing:

object Object1 = new Thing();
object Object2 = Object1;

You get a second reference to the object you instantiated in the first line. What you need to do is look at "Thing" and see if it has a Copy, Clone or similarly named method and use that:

object Object1 = new Thing();
object Object2 = Object1.Copy();

For example, DataTable offers both Copy and Clone methods, where Copy duplicates both the structure of the DataTable and the data and Clone only duplicates the structure.


Either implement Clone() on your class or use Object.MemberwiseClone()

http://msdn.microsoft.com/de-de/library/system.object.memberwiseclone(VS.80).aspx


If you want a copy of an object the question is always: How deep will the copy occur? What should happen to the objects within my object. Should these be copied also and if yes what should happen to their references??

For more informations take at starting point this blog post from Brad Abrams.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜