浅复制或深层复制? [英] Shallow copy or Deep copy?
问题描述
我是一个有点新的拷贝一个对象到另一个的这两种方法。我很困惑,无法辨认出深拷贝和浅拷贝..我已经通过很多关于这个理论的消失之间的主要区别,但我需要有适当的例子..
解释我的计划中,我复制一个对象到另一个。 - >
A级
{
公众诠释A = 0;
公共无效显示()
{
Console.WriteLine(a的值为+一);
}
}
类节目
{
静态无效的主要(字串[] args)
{
一个OB1 =新的A() ;
ob1.a = 10;
ob1.display();
一个OB2 =新的A();
OB2 = OB1;
ob2.display();
Console.Read();
}
}
这是一个浅拷贝或深拷贝?任何人都可以请提供合理的答案。如果它是一个深拷贝,那么请对这一计划做对象复制同样的工作,和周围的其他方式提供浅拷贝代码..
如果该上面是一个浅拷贝,那么即使这应该是一个浅拷贝 - >
A OB1 =新的A();
ob1.a = 10;
ob1.display();
一OB2 = OB1;
ob2.a = 444;
ob1.display();
从链接的here
浅拷贝复制尽可能少。一个
集合的浅表副本是集合结构的副本,而不是元素。
,其中A浅拷贝,两个集合现在共享个人
元素。
深拷贝复制的一切。集合的深层副本是所有复制的原始集合
的元素的两个
系列。
块引用>
你的榜样是创建浅拷贝
A OB1 =新的A();
ob1.a = 10;
一个OB2 =新的A();
OB2 = OB1;
ob1.a = 5; //< - 如果这条线后,看到ob2.a的价值,这将是5,
深层复制将是 -
A OB1 =新的A();
ob1.a = 10;
一个OB2 =新的A();
ob2.a = ob1.a;
ob1.a = 5; //< - 如果这条线后,看到ob2.a的价值,这将是10
I am a bit new to these two methods of copying one object into the other. I am confused and unable to spot out the major difference between deep copy and shallow copy.. I had gone through a lots of theory regarding this, but I need explanation with proper examples.. I have program in which I copy one object into another. -->
class A { public int a = 0; public void display() { Console.WriteLine("The value of a is " + a); } } class Program { static void Main(string[] args) { A ob1 = new A(); ob1.a = 10; ob1.display(); A ob2 = new A(); ob2 = ob1; ob2.display(); Console.Read(); } }
Is this a shallow copy or a deep copy ? Can anyone please provide the answer with reason. If it is a deep copy, then please provide the code for shallow copy for this program doing the same job of object copying, and the other way around..
If the above is a shallow copy, then even this should be a shallow copy-->
A ob1 = new A(); ob1.a = 10; ob1.display(); A ob2 = ob1; ob2.a = 444; ob1.display();
解决方案From the link here
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
Your example is creating a shallow copy.
A ob1 = new A(); ob1.a = 10; A ob2 = new A(); ob2 = ob1; ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 5.
Deep copy will be -
A ob1 = new A(); ob1.a = 10; A ob2 = new A(); ob2.a = ob1.a; ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 10.
这篇关于浅复制或深层复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!