Deep Copy in C#

后端 未结 8 630
独厮守ぢ
独厮守ぢ 2021-02-05 20:36

MSDN gives this example of a deep copy (http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx)

public class Person 
{
    public int Age;
           


        
8条回答
  •  一向
    一向 (楼主)
    2021-02-05 21:08

    MemberwiseClone does create a new object and copies all non static fields. In case of reference types this means copying the references. So yes, after a member wise clone the fields of the new object point to the same objects as the fields of the original object (for reference types). That is why the example in the MSDN create a new instance of the IdInfo: To create a copy of that object as well.

    Your DeepCopy implementation is broken because it does not copy all fields, but if it would then the result would not be different from the MemberwiseClone solution.

    This question might also be an interesting read for you: Create a Deep Copy in C#

提交回复
热议问题