Copy C# object along with reference

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, ie 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.

链接地址: http://www.djcxy.com/p/40766.html

上一篇: 复杂的第三方对象/类的深层副本

下一篇: 将C#对象与引用一起复制