Deep Copy in C#

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

    In the example that you specified, the values of Age and Name would be zero/blank.

    This is due to the fact that you instantiate the Person object, but never set the values of these fields.

    From Object.MemberwiseClone Method

    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. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

    So as you can see, using the MemberwiseClone method, your Age/Name fields will also be copied/cloned.

提交回复
热议问题