Deep Copy in C#

后端 未结 8 629
独厮守ぢ
独厮守ぢ 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:27

    Your DeepCopy will not copy the Age and Name fields from the object being copied. They will get their default(T) values instead (Age = 0, Name = null).

    MemberwiseClone does create a new object just like you did, but it also copies the fields:

    Person other = new Person();

    other.Age = this.Age;

    other.Name = this.Name;

    As int is a value type it will be copied to the new object. The Name field will reference the same string that was referenced by Name - if that is not okay then you would need to Clone() that and set the reference in your DeepCopy() method just like IdInfo.

    According to MSDN: The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object.

    0 讨论(0)
  • 2021-02-05 21:30

    Your new method does not copy the value of this.Age and this.Name, so i think it's even not called copy.

    0 讨论(0)
提交回复
热议问题